我有这个简单的NodeJs代码来处理来自任何其他来源的post请求
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发送post请求时,我在终端中得到了类似于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
发布于 2021-02-13 21:22:22
如果主体中的数据是JSON对象,您可以只删除块中的toString,并用JSON.parse替换解析,如下所示:
let body = "";
request.on("data", (chunk) => {
body += chunk; // convert Buffer to string
});
request.on("end", () => {
const result = JSON.parse(body);
console.log(result);
response.end("ok");
});
如果您从postman发送的数据选择了"raw“和"JSON",并在body中发送了一个对象,则可以正常工作:
{
"user": "john"
}
如果数据以"x-www-form-urlencoded“的形式发送,那么使用querystring的parse方法的当前方法应该工作得很好。
简而言之,解决方案是修改发送到服务器的请求的Content-Type头。
https://stackoverflow.com/questions/66189950
复制相似问题