kevin kevin - 5 months ago 22
JSON Question

when i use ajax post json to web server(Nodejs), but the web server can't receive the data from client

the client code :

self.getjson = function () {
var timeinfo = new Object();
timeinfo.time = self.time;
timeinfo.address = self.address;
timeinfo.info = self.info;

return JSON.stringify(timeinfo);
};

alert(self.getjson());

$.ajax({
type: "POST",
//beforeSend:function(){$(".info").fadeIn('slow').html("正在提交,请稍后");},
url:'/user/add/timetemp',
data: self.getjson(),
beforeSend: function (xhr) {

xhr.setRequestHeader("Content-Type", "application/json");
},
success: function(data){

}

})


the server code app.js:

router.route('/user/add/timetemp')
.post(function(req,res){

console.log(req.body); // your JSON
res.send(req.body); // echo the result back


});

the answer from client:
enter image description here
there has data in the client.

the answer from server:

but the server is null

Answer

From the documentation:

req.body

Contains key-value pairs of data submitted in the request body. By default, it is undefined, and is populated when you use body-parsing middleware such as body-parser and multer.

(My emphasis.) It continues with:

The following example shows how to use body-parsing middleware to populate req.body.

var app = require('express')();
var bodyParser = require('body-parser');
var multer = require('multer'); // v1.0.5
var upload = multer(); // for parsing multipart/form-data

app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded

app.post('/profile', upload.array(), function (req, res, next) {
  console.log(req.body);
  res.json(req.body);
});

Side notes:

1. All of these variables on self are global variables. Global variables are a Bad Thing™. :-) Generally best to put your code in a scoping function and use locals within that scoping function.

2. new Object is almost never needed. Your getjson function can be much simpler:

self.getjson = function () {
    return JSON.stringify({
        time: self.time,
        address: self.address,
        info: self.info
    });
};

or (slightly more convenient when debugging):

self.getjson = function () {
    var timeinfo = {
        time: self.time,
        address: self.address,
        info: self.info
    };
    return JSON.stringify(timeinfo);
};

3. There's no need for your beforeSend callback on ajax; just use the built-in contentType option:

$.ajax({
    type: "POST",
    //beforeSend:function(){$(".info").fadeIn('slow').html("正在提交,请稍后");},
    url: '/user/add/timetemp',
    data: self.getjson(),
    contentType: 'application/json',
    success: function(data) {

    }
});
Comments