一、使用 `http` 模块处理请求方法
1. 创建 HTTP 服务器
const http = require("http");
const server = http.createServer((req, res) => {
// 处理不同的请求方法
switch (req.method) {
case "GET":
handleGetRequest(req, res);
break;
case "POST":
handlePostRequest(req, res);
break;
case "PUT":
handlePutRequest(req, res);
break;
case "DELETE":
handleDeleteRequest(req, res);
break;
default:
handleUnsupportedMethod(req, res);
}
});
// 监听端口
server.listen(3000, () => {
console.log("Server running on port 3000");
});
2. 处理 GET 请求
function handleGetRequest(req, res) {
// 设置响应头
res.writeHead(200, { "Content-Type": "text/plain" });
// 发送响应内容
res.end("This is a GET request");
}
3. 处理 POST 请求
function handlePostRequest(req, res) {
let body = "";
// 接收请求体数据
req.on("data", (chunk) => {
body += chunk.toString();
});
req.on("end", () => {
// 设置响应头
res.writeHead(200, { "Content-Type": "text/plain" });
// 发送响应内容
res.end(`This is a POST request with body: ${body}`);
});
}
4. 处理 PUT 请求
function handlePutRequest(req, res) {
let body = "";
req.on("data", (chunk) => {
body += chunk.toString();
});
req.on("end", () => {
// 设置响应头
res.writeHead(200, { "Content-Type": "text/plain" });
// 发送响应内容
res.end(`This is a PUT request with body: ${body}`);
});
}
5. 处理 DELETE 请求
function handleDeleteRequest(req, res) {
// 设置响应头
res.writeHead(200, { "Content-Type": "text/plain" });
// 发送响应内容
res.end("This is a DELETE request");
}
6. 处理不支持的请求方法
function handleUnsupportedMethod(req, res) {
// 设置响应头
res.writeHead(405, { "Content-Type": "text/plain" });
// 发送响应内容
res.end("Method Not Allowed");
}
二、使用 `express` 框架处理请求方法
1. 安装 `express` 框架
npm install express
2. 创建 `express` 服务器
const express = require("express");
const app = express();
// 处理 GET 请求
app.get("/", (req, res) => {
res.send("This is a GET request");
});
// 处理 POST 请求
app.post("/", (req, res) => {
res.send("This is a POST request");
});
// 处理 PUT 请求
app.put("/", (req, res) => {
res.send("This is a PUT request");
});
// 处理 DELETE 请求
app.delete("/", (req, res) => {
res.send("This is a DELETE request");
});
// 监听端口
app.listen(3000, () => {
console.log("Server running on port 3000");
});