这个JSON结构何时转换为所有字符串?

Joe*_*man 16 jquery jsonp node.js express

我正在向我的node/express服务器发送JSON结构并将对象保存到数据库中.问题是我发送带有整数和布尔值的JSON,但所有内容都保存为字符串.

这是我的节点/快递代码:

var express = require('express');

var app = express();
app.enable("jsonp callback");
app.use(express.bodyParser());

// allow cross origin scripting to get data from devices directly
app.all('*', function(req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
  res.header('Access-Control-Allow-Headers', 'Content-Type');
  next();
});

app.post('/departures', function(req, res) {

/* I started using this to convert back to integers - but need to solve the problem
    for (var i in req.body.data) {
      req.body.data[i].siteid = parseInt(req.body.data[i].siteid);
    }
*/
    console.log('saving data '+JSON.stringify(req.body.data));
    positionProvider.save(req.body.data, function(){
      res.json({status:'success'});
    })
});
Run Code Online (Sandbox Code Playgroud)

这是我用jquery进行POST的方式:

    var data = [{"siteid":123}];

    $.ajax({
        type: 'POST',
        url: serverUrl + '/departures',
        data: {
            data: data
        },
        success: function(resp) {
            alert('saved departure data '+JSON.stringify(data))
        },
        error: function(err) {
            console.log('error posting to server...');
            console.log(err);
        }
    });
Run Code Online (Sandbox Code Playgroud)

jquery端报告它发送了{"siteid":123},但节点端报告它收到{"siteid":"123"}.

整数转换为字符串在哪里?

cjo*_*ohn 12

您的数据将转换为字符串,作为从客户端发送到服务器的产品.请记住,客户端和服务器实际上并不是以JSON进行通信,而是以文本或二进制数据进行通信.服务器(Express?)隐式解释作为字符串发送的数据,如果包含content-type: application/json请求标头,则将其转换为JSON .如果您希望数据以特定格式保留,则需要明确地在服务器上键入check和convert.

TLDR(评论); 不依赖客户端发送有效数据.在将其保存到数据库之前清理它.


小智 10

我遇到了同样的问题.字符串化JSON时,jQuery $ .post和$ .ajax将整数转换为字符串.您可以通过查看服务器端的数据来验证它.服务器收到类似{"age":"3"}的内容,而你真的想要{"age":3}.

有效的解决方案是避免给出jQuery纯对象,但是给它一个字符串:

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