考虑以下对 Node.js 服务器的 HTTP POST
调用:
curl -H "Content-Type: application/json" \
-X POST \
-d '{"jsonKey":"jsonValue"}' \
'http://localhost:8080?abcd=efgh'
我想访问 POST 请求的 URL 参数和 JSON 负载。
通过导入 url.parse
访问 URL 参数非常简单:
var server = http.createServer(function(req, res) {
// Parse the params - prints "{ abcd: 'efgh' }"
var URLParams = url.parse(req.url, true).query;
console.log(URLParams);
// How do I access the JSON payload as an object?
}
但是如何使用 native Node.js 库(无需任何 npm
导入)访问 JSON 负载?
我尝试了什么
- 将
req
打印到console.log
,但没有找到 POST 对象 - 阅读
req
的文档,其类型为http.IncomingMessage
最佳答案
来自文档:
When receiving a POST or PUT request, the request body might be important to your application. Getting at the body data is a little more involved than accessing request headers. The request object that's passed in to a handler implements the ReadableStream interface. This stream can be listened to or piped elsewhere just like any other stream. We can grab the data right out of the stream by listening to the stream's 'data' and 'end' events.
https://nodejs.org/en/docs/guides/anatomy-of-an-http-transaction/#request-body
var server = http.createServer(function(req, res) {
// Parse the params - prints "{ abcd: 'efgh' }"
var URLParams = url.parse(req.url, true).query;
console.log(URLParams);
// How do I access the JSON payload as an object?
var body = [];
req.on('data', function(chunk) {
body.push(chunk);
}).on('end', function() {
body = Buffer.concat(body).toString();
if (body) console.log(JSON.parse(body));
res.end('It Works!!');
});
});
关于json - 从 Node.js 服务器 native 访问 JSON POST 负载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43161537/