使用jQuery向Express发送JSON数据POST请求

23

当我从客户端向运行express的node服务器发送JSON数据时,我遇到了问题。

这是一个演示我的问题的简单服务器:

var express = require('express');

var app = express();

app.configure(function(){   
    app.use(express.bodyParser());
    app.use(app.router);
    app.use(express.logger());
});

app.listen(80);

app.post('/', function(req,res){
    console.log(req.body);
    console.log(req.body.number + 1);
});

该服务器只是将所有的POST数据记录到控制台。

如果我将以下内容粘贴到Chrome开发控制台中: $.post('/', {number:1});

服务器会打印出:

This server simply logs all POST data to the console.

If I then paste the following into chrome's development console: $.post('/', {number:1});

The server prints out:

{ number: '1' }
11

我该如何防止传递的数字被解释为字符串?这与我使用的bodyParser中间件有关吗?

非常感谢任何帮助!!

1个回答

41

$.post 发送的是 url-encoded 数据,实际发送的数据是 number=1,然后使用 bodyParser 中间件进行解析。

如果要发送 json,你需要使用 JSON.stringify({number:1})

不幸的是,使用 $.post 无法设置适当的 Content-Type 标头(express 会自动处理),因此最好使用:

$.ajax({
    url: '/', 
    type: 'POST', 
    contentType: 'application/json', 
    data: JSON.stringify({number:1})}
)

3
别忘了添加contentType: 'application/json'头部,否则在服务器端req.body中将没有任何数据。 - Christiaan Westerbeek
@soulcheck,你能看一下我的问题吗?链接在这里:https://stackoverflow.com/questions/47085674/send-object-to-nodejs-using-post-method。它和这个问题类似,但我需要发送另一个属性与数组一起。 - Viet
Christiaan Westerbeek对于金钱的评论。不要将json:true与contentType:'application / json'混淆。这不是同一件事。如果您想让它起作用,请添加contentType:'application / json'。 - codemonkey

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接