【问题标题】:Nodejs Express req.body is empty and header nullNodejs Express req.body 为空且标头为空
【发布时间】:2021-03-19 17:34:05
【问题描述】:

我正在检索一个发布请求正文,以便我可以将正文中的参数添加到我的数据库中。

起初我收到一个错误 SyntaxError: Unexpected token ' in JSON at position 0 at JSON.parse (<anonymous>) 但我添加了这一行 applctn.use(express.urlencoded({ extended: true })); // to support URL-encoded bodies 现在我得到一个空的正文。

我的代码如下所示:

const express = require("express");
const moment = require("moment");
const db = require("./dbconnection.js"); //reference of dbconnection.js
var bodyParser = require("body-parser");

const applctn = express();

applctn.use(bodyParser.urlencoded({extended: true}));

applctn.post("/hl7_message", function(req, res) {

    var jsonObj = JSON.stringify(req.body);

    console.log(req);

当我添加 ```app.use(bodyParser.json()); // 支持 JSON 编码的正文

 ```SyntaxError: Unexpected token ' in JSON at position 0 at JSON.parse (<anonymous>) 

任何关于我如何检索正文内容的建议/提示将不胜感激。

my response

【问题讨论】:

  • 尝试使用 applctn.use(express.json()) 这可能是您的设置中缺少的东西。
  • @dhruv479,当我补充说我得到这个错误SyntaxError: Unexpected token ' in JSON at position 0 at JSON.parse (&lt;anonymous&gt;)

标签: javascript node.js express


【解决方案1】:

您忘记添加applctn.use(bodyParser.json())。这是解决方案:

const express = require("express");
const moment = require("moment");
const db = require("./dbconnection.js"); //reference of dbconnection.js
var bodyParser = require("body-parser");

const applctn = express();
applctn.use(bodyParser.json());
applctn.use(bodyParser.urlencoded({extended: true}));

applctn.post("/hl7_message", function(req, res) {
 console.log(req.body);
 res.send({code:200,message:"success"})
})

applctn.listen(3000,function(){
  console.log("running");
});

【讨论】:

    猜你喜欢
    • 2018-04-30
    • 2019-02-08
    • 2016-02-15
    • 2020-12-17
    • 2020-01-08
    • 1970-01-01
    • 2018-11-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多