我正在尝试通过 AJAX POST 成功地从浏览器到 Nodejs 服务器来回 ping 一个对象。但是,我没有运气,因为从浏览器到服务器的中间人将该对象解释为空白( {}
)。有人知道我做错了什么吗?
客户:
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);
谢谢
最佳答案
我知道这有点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));
有点老套,但对我有用:)
希望这对你有帮助:)
关于javascript - Ajax POST 到 Nodejs 给出空白对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23728033/