从Node.js服务器本地访问JSON POST有效内容
考虑下面的一个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? }
但是,如何使用本地Node.js库(不包括任何npm
导入)来访问JSON负载?
我试过了什么
- 打印
req
到console.log
,但没有findPOST对象 - 阅读
req
的文档,这是typeshttp.IncomingMessage
req
是一个stream,所以你如何访问它取决于你想如何使用它。 如果您只是想将其作为文本并将其parsing为JSON,则可以执行以下操作:
let data = ""; req.on("readable", text => data += text); req.on("end", () => { try { const json = JSON.parse(data); } catch (err) { console.error("request body was not JSON"); } /* now you can do something with JSON */ });
从文档:
当收到POST或PUT请求时,请求主体可能对你的应用程序很重要。 获取身体数据比访问请求标题要复杂一点。 传递给处理程序的请求对象实现了ReadableStream接口。 这个stream可以像任何其他stream一样在其他地方被监听或者传送。 我们可以通过监听stream的“数据”和“结束”事件来从stream中获取数据。
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!!'); }); });