Nodejs接收字符串而不是布尔值(Nodejs receiving string instead of boolean)

编程入门 行业动态 更新时间:2024-10-28 13:24:53
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: true

How 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) } });

更多推荐

本文发布于:2023-04-28 13:29:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1332435.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   而不是   布尔值   Nodejs   string

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!