繁体   English   中英

Nodejs Express req.body 为空且 header null

[英]Nodejs Express req.body is empty and header null

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

At first I was getting an error SyntaxError: Unexpected token ' in JSON at position 0 at JSON.parse (<anonymous>) but i added this line applctn.use(express.urlencoded({ extended: true })); // to support URL-encoded bodies 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>) 

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

我的回复

您忘记添加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");
});

暂无
暂无

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

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