在 Web 开发中,处理 GET 和 POST 请求是非常常见的操作。Node.js 提供了方便的模块来处理这些请求,让开发变得更加简单和高效。
处理 GET 请求
在 Node.js 中处理 GET 请求非常简单,可以使用内置的 http 模块。下面是一个简单的例子:
// www.javascriptcn.com code example
const http = require('http');
http.createServer((req, res) => {
if (req.method === 'GET' && req.url === '/hello') {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello, world!');
} else {
res.writeHead(404, {'Content-Type': 'text/plain'});
res.end('Not Found');
}
}).listen(3000);
console.log('Server running at http://localhost:3000/');在上面的代码中,我们创建了一个简单的 HTTP 服务器,当收到 GET 请求并且 URL 是 '/hello' 时,返回 'Hello, world!',否则返回 'Not Found'。
处理 POST 请求
处理 POST 请求比处理 GET 请求稍微复杂一些,因为 POST 请求通常会传递数据。我们可以使用第三方模块 body-parser 来解析 POST 请求中的数据。下面是一个简单的例子:
// www.javascriptcn.com code example
const http = require('http');
const bodyParser = require('body-parser');
http.createServer((req, res) => {
if (req.method === 'POST' && req.url === '/login') {
let body = '';
req.on('data', (chunk) => {
body += chunk;
});
req.on('end', () => {
let data = JSON.parse(body);
console.log(data);
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify({message: 'Login successful'}));
});
} else {
res.writeHead(404, {'Content-Type': 'text/plain'});
res.end('Not Found');
}
}).listen(3000);
console.log('Server running at http://localhost:3000/');在上面的代码中,我们创建了一个 HTTP 服务器,当收到 POST 请求并且 URL 是 '/login' 时,解析请求中的数据,并返回一个 JSON 响应。
处理 GET 和 POST 请求是 Node.js 开发中的基础操作,掌握这些知识将有助于你更好地开发 Web 应用程序。