Skip to main content

POST

GET 请求参数直接通过 query 获取,不存在传递参数数据情况;而 POST 等请求参数,参数需要从请求体获取时,属于为大文件传输,所以需要考虑异步情况。

通过监听数据的“开始”和“结束”,对 chunk 数据片段进行拼接,当然传输完成返回全部数据。

注意:传输时数据为 string,传输完成需要 JSON.parse 反序列化转为 Objecjt 对象

// 用于处理 POST 请求(POST、DELETE...)
const getPostData = (req) => {
const promise = new Promise((resolve, reject) => {
// 防御:处理非 GET 请求,GET 请求参数直接通过 query 获取
if (req.method === "GET") {
console.log("GET 请求");
resolve({});
return;
}

// 请求类型:仅处理 json 数据类型
if (req.headers["content-type"] !== "application/json") {
console.log("content-type 非 json");
resolve({});
return;
}

// 数据
let postData = "";

// 监听数据开始:对 chunk 数据片段进行拼接
req.on("data", (chunk) => {
postData += chunk.toString();
});

// 监听数据结束:反
req.on("end", () => {
// 防御:无参数
if (!postData) {
console.log("参数为空");
resolve({});
return;
}
// 返回完整数据
resolve(JSON.parse(postData));
});
});
return promise;
};

使用方法

// 处理 post data
getPostData(req).then((postData) => {
// req 声明 body 字段并赋予 postData 数据
// 下面所有接口都可以获取到 postData 数据
req.body = postData;

// 处理 timeline 路由
const timelineData = handleTimelineRouter(req, res);

if (timelineData) {
timelineData.then((data) => {
res.end(JSON.stringify(data));
});
return;
}

// 处理未命中路由,返回 404
res.writeHead(404, { "Content-Type": "text/plain" });
res.write("404 Not Found\n");
res.end();
});