【发布时间】:2021-02-13 21:07:41
【问题描述】:
我有这个简单的 NodeJs 代码来处理从任何其他来源(如 Postman)发送的发布请求
const http = require("http");
const { parse } = require("querystring");
const server = http.createServer(function (request, response) {
console.dir(request.param);
if (request.method === "POST") {
let body = "";
request.on("data", (chunk) => {
body += chunk.toString(); // convert Buffer to string
});
request.on("end", () => {
const result = parse(body);
console.log(result);
response.end("ok");
});
}
});
const port = 8080;
const host = "127.0.0.1";
server.listen(port, host);
当我从 Postman 发送带有 user:foo 之类的表单数据的发布请求时,我在终端中得到这样的结果
[Object: null prototype] {
'----------------------------908153651530187984286555\r\nContent-Disposition: form-data; name': '"user"\r\n\r\nfoo\r\n----------------------------908153651530187984286555--\r\n'
当我跑步时
console.log(result.user)
我收到undefined
我把解析体const result = parse(body);改成了这个
const result = JSON.parse(JSON.stringify(body))
我得到了
----------------------------939697314758807513697606
Content-Disposition: form-data; name="user"
foo
----------------------------939697314758807513697606--
但还是收不到result.user
如何通过将此类数据转换为对象来处理此类数据并获得这样的用户result.user
【问题讨论】: