发布JSON以使用jQuery进行表达 [英] POSTing json to express using jQuery

查看:75
本文介绍了发布JSON以使用jQuery进行表达的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从客户端向运行express的节点服务器发送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});

服务器打印出:

{ number: '1' }
11

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

任何帮助表示赞赏!

解决方案

$.post发送url编码的数据,所以真正发送的是number=1,然后由bodyParser中间件对其进行尽可能好的解析和解析. /p>

要发送json,您必须使用JSON.stringify({number:1}).

不幸的是,使用$.post不会设置适当的Content-Type标头(无论如何,express都会处理它),因此最好使用:

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

I'm having an issue when sending JSON data from my client to a node server running express.

Here's a simple server that demonstrates my issue:

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

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

How can I stop the number I'm passing being interpreted as a string? Is it something to do with the bodyParser middleware I'm using?

Any help appreciated!!

解决方案

$.post sends url-encoded data, so what is really sent is number=1, which then is parsed as well as it can by bodyParser middleware.

To send json you have to use JSON.stringify({number:1}).

Using $.post unfortunately won't set the appropriate Content-Type header (express will handle it anyway), so it's better to use:

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

这篇关于发布JSON以使用jQuery进行表达的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆