json - 从 Node.js 服务器 native 访问 JSON POST 负载

标签 json node.js post payload

考虑以下对 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/

相关文章:

php - 使用 GET 执行数据库操作的快速、简单且安全的方法

javascript - 将csrf输入添加到tinyMCE图像上传laravel

javascript - 在 jQuery Ajax 中,数据类型 : jsonp gives "SyntaxError: unterminated string literal" while dataType:json works fine?

MYSQL/JSON : compare an array with the list of a column in JSON format and count the number of terms that match

node.js - 限制 Express 服务器

node.js - 使用 mongodb 获取用户所有帖子的点赞数

node.js - 【M1芯片Mac】Nuxt构建太慢

javascript - `fetch` 请求未显示所需结果,`ajax` 请求显示所需结果

java - 将字符串值转换为类型

mysql - 时间戳的json格式