处理 HTTP GET 请求
const http = require('http');
const url = require('url');
const server = http.createServer((req, res) => {
// 解析请求的 URL
const parsedUrl = url.parse(req.url, true);
// 获取路径和查询参数
const path = parsedUrl.pathname;
const query = parsedUrl.query;
// 处理不同路径的 GET 请求
if (path === '/hello') {
// 返回简单的 Hello 消息
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello, Node.js!');
} else {
// 处理未知路径
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not Found');
}
});
const PORT = 3000;
server.listen(PORT, () => {
console.log(`Server is listening on port ${PORT}`);
});
处理 HTTP POST 请求
const http = require('http');
const querystring = require('querystring');
const server = http.createServer((req, res) => {
// 处理 POST 请求
if (req.method === 'POST') {
let body = '';
// 接收请求的数据
req.on('data', (chunk) => {
body += chunk;
});
// 处理完数据后触发
req.on('end', () => {
// 解析 POST 数据
const postData = querystring.parse(body);
// 处理 POST 数据
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end(`Received data: ${JSON.stringify(postData)}`);
});
} else {
// 处理不是 POST 请求的情况
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not Found');
}
});
const PORT = 3000;
server.listen(PORT, () => {
console.log(`Server is listening on port ${PORT}`);
});
在上述例子中,我们创建了一个简单的 HTTP 服务器,通过 http 模块监听指定端口。对于 GET 请求,我们通过解析 URL,根据路径返回不同的响应。对于 POST 请求,我们通过监听 data 事件接收请求数据,然后在 end 事件中处理这些数据。
请注意,这只是一个基本的例子,实际中你可能会使用更高级的框架(例如 Express)来简化和增强处理请求的过程。
转载请注明出处:http://www.pingtaimeng.com/article/detail/4745/Node.js