对nodejs的Ajax POST给出了空白对象

时间:2014-05-18 23:59:23

标签: javascript ajax node.js

我试图通过AJAX POST成功地将一个对象从浏览器来回ping到nodejs服务器。但是,我没有运气,因为从浏览器到服务器的中间人将对象解释为空白({})。有人知道我做错了吗?

客户端:

var xhr = new XMLHttpRequest();
xhr.open("POST", "/save");
xhr.onload = function(){
    console.log(xhr.responseText); //See what the server ponged
}
xhr.send({"foo": "bar"}); //Ping the object

服务器

var express = require('express');
var app = express();

app.configure(function() {
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(express.static(__dirname + '/public'));
  app.use(app.router);
});
app.configure('development', function() {
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

app.configure('production', function() {
  app.use(express.errorHandler());
});

app.post('/save', function(req, res){  //When server receives ping
    res.send(req.body);    // Pong the object back
});

var port = process.env.PORT || 3000;

var server = app.listen(port);

由于

1 个答案:

答案 0 :(得分:1)

我知道这有点hacky但有效:

在您的客户端执行此操作:

var xhr = new XMLHttpRequest();
xhr.open("POST", "/save");
xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xhr.onload = function(){
    console.log(JSON.parse(xhr.responseText)); //See what the server ponged
}
xhr.send('{"foo":"bar"}');

并在服务器端发送:

res.send(Object.keys(req.body));

有点hacky但为我工作:)

希望这可以帮助你:)