简体   繁体   English

从Node.js服务器本地访问JSON POST有效负载

[英]Natively access JSON POST payload from Node.js server

Consider the following HTTP POST call to a Node.js server: 考虑以下对Node.js服务器的HTTP POST调用:

curl -H "Content-Type: application/json" \
     -X POST \
     -d '{"jsonKey":"jsonValue"}' \
     'http://localhost:8080?abcd=efgh'

I would like to access both the URL parameters and the JSON payload of the POST request. 我想访问URL参数和POST请求的JSON有效负载。

Accessing the URL params is pretty straightforward by importing url.parse : 通过导入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?
}

But how do I access the JSON payload, using native Node.js library (without any npm import)? 但是,如何使用本机Node.js库(没有任何npm导入)访问JSON有效负载?

What have I tried 我尝试了什么

  • Printed req to console.log , but did not find the POST object 印刷reqconsole.log ,但没有找到POST对象
  • Read the documentation of req , which is of type http.IncomingMessage 阅读req的文档,该文档的类型为http.IncomingMessage

From documentation: 从文档:

When receiving a POST or PUT request, the request body might be important to your application. 当接收到POST或PUT请求时,请求主体对于您的应用程序可能很重要。 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. 传递给处理程序的请求对象实现ReadableStream接口。 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 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!!');
        });
});

req is a stream so how you access it depends on how you want to use it. req是一个流,因此如何访问它取决于您要如何使用它。 If you just want to get it as text and parse that as JSON, you can do the following: 如果只想将其获取为文本并将其解析为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 */
}); 

Just as an addition; 只是作为补充; if you'd like to create an object from the POST body, I am using the following piece of code: 如果您想从POST主体创建对象,则使用以下代码:

const body2Obj = chunk => {
  let body = {};
  let string = chunk.toString();
  if (!string.trim()) return body;
  string.split('&').forEach(param => {
    let elements = param.split('=');
    body[elements[0]] = elements[1];
  });
  return body;
};

And then use that as already explained by stdob-- above: 然后使用上面的stdob--所解释的:

var body = [];
req.on('data', chunk => {
  body.push(chunk);
}).on('end', () => {
  body = Buffer.concat(body);
  body = body2Obj(body);
  // ...
});

I prefer this solution instead of using an oversized third-party module for just parsing the body of the request (sometimes, people suggest that for some reason). 我更喜欢这种解决方案,而不是使用超大的第三方模块来仅解析请求的主体(有时,出于某些原因,人们建议这样做)。 Might be that there's a shorter version of mine. 可能是我的版本较短。 Of course, this works only for url-encoded formatted bodies. 当然,这仅适用于url编码的格式化主体。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM