[英]Nodejs Express req.body is empty and header null
I am working on retrieving a post request body so that i can add the arguments in the body to my database.我正在检索一个发布请求正文,以便我可以将正文中的 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
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
and now i get an empty body. applctn.use(express.urlencoded({ extended: true })); // to support URL-encoded bodies
,现在我得到一个空正文。
My code looks like this:我的代码如下所示:
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);
When i add ```app.use(bodyParser.json());当我添加 ```app.use(bodyParser.json()); // to support JSON-encoded bodies
// 支持 JSON 编码的主体
```SyntaxError: Unexpected token ' in JSON at position 0 at JSON.parse (<anonymous>)
Any advise /tips on how i can retrieve the body contents will be appreciated.任何有关我如何检索正文内容的建议/提示将不胜感激。
You forgot to add applctn.use(bodyParser.json())
.您忘记添加
applctn.use(bodyParser.json())
。 Here is the solution:这是解决方案:
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.