Nodejs接收字符串而不是布尔值(Nodejs receiving string instead of boolean)
我试图在对象中使用布尔值向节点服务器发送http请求。
我收到节点req.body :
somekey: "true"代替
somekey: true怎么修好?
I am trying to send http request to node server with boolean value in the object.
I receive in node req.body:
somekey: "true"instead of
somekey: trueHow can it be fixed?
最满意答案
使用body-parser NPM包。
var bodyParser = require('body-parser'); //You middleware should have this before the handlers. app.use(bodyParser.json());编辑:
这就是你的AJAX请求应该是什么样子。 您可能缺少请求正文的JSON.stringify部分或未在请求标头中设置Content-Type: application/json 。 这对我有用。
$.ajax({ url: "https://example.com/hello/login', type: 'POST', headers: { "Content-Type": "application/json" }, data: JSON.stringify({ somekey: true }), success: function(result) { console.log(result) } });Use body-parser NPM package.
var bodyParser = require('body-parser'); //You middleware should have this before the handlers. app.use(bodyParser.json());EDIT:
This is what your AJAX request should look like. You're probably missing the JSON.stringify part for request body or not setting Content-Type: application/json in your request header. This works for me.
$.ajax({ url: "https://example.com/hello/login', type: 'POST', headers: { "Content-Type": "application/json" }, data: JSON.stringify({ somekey: true }), success: function(result) { console.log(result) } });更多推荐
发布评论