面试题答案
一键面试在Node.js的HTTP模块中,可以通过request
对象的method
属性来区分不同类型的HTTP请求,以下是实现思路和关键代码示例:
-
实现思路:
- 创建HTTP服务器。
- 在请求处理函数中,通过
request.method
判断请求类型。 - 根据不同的请求类型,进行相应的处理。
-
关键代码:
const http = require('http');
const server = http.createServer((request, response) => {
if (request.method === 'GET') {
// 处理GET请求
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('This is a GET request');
} else if (request.method === 'POST') {
let body = '';
request.on('data', (chunk) => {
body += chunk.toString();
});
request.on('end', () => {
// 处理POST请求,这里简单输出请求体
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('This is a POST request. Body: ' + body);
});
} else {
// 处理其他请求类型
response.writeHead(405, {'Content-Type': 'text/plain'});
response.end('Method Not Allowed');
}
});
const port = 3000;
server.listen(port, () => {
console.log(`Server running on port ${port}`);
});
上述代码创建了一个简单的HTTP服务器,当接收到请求时,根据request.method
判断请求类型。如果是GET
请求,直接返回固定信息;如果是POST
请求,收集请求体数据并返回包含请求体的信息;对于其他请求类型,返回405 Method Not Allowed
。