【问题标题】:NodeJs how to parse post body sent from PostmanNodeJs如何解析从邮递员发送的帖子正文
【发布时间】:2021-02-13 21:07:41
【问题描述】:

我有这个简单的 NodeJs 代码来处理从任何其他来源(如 Postman)发送的发布请求

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 发送带有 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

【问题讨论】:

    标签: node.js postman http-post


    【解决方案1】:

    如果你的 body 中的数据是 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");
      });
    

    如果您从邮递员那里发送数据,选择“raw”和“JSON”,这将正常工作,在正文中发送如下对象:

    {
        "user": "john"
    }
    

    如果数据以“x-www-form-urlencoded”形式发送,您当前的方法(使用查询字符串的 parse 方法)应该可以正常工作。

    简而言之,解决方案是修改您发送到服务器的请求的 Content-Type 标头。

    【讨论】:

      猜你喜欢
      • 2018-11-23
      • 1970-01-01
      • 2021-05-23
      • 1970-01-01
      • 2021-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-16
      相关资源
      最近更新 更多