javascript - Ajax POST 到 Nodejs 给出空白对象

标签 javascript ajax node.js

我正在尝试通过 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/

相关文章:

php - Acquire_lock() 不起作用。机器人仍然快速发送请求。 PHP+AJAX

javascript - 如何使用ajax、php session 增加数量?

javascript "classes"与数组跟踪器

在 iOS 上调用 "TypeError: cancelled"时出现 Javascript "fetch"错误

javascript - javascript new Date() 构造函数对相同不同格式字符串的不明确行为

node.js - 使用 Apache 运行 NodeJS 应用程序

javascript - 如何使用 javascript 在 jade 文件输出中动态插入标签?

javascript - 左边距是否为 :2px; render faster than margin:0 0 0 2px;?

javascript - 在学习 Ajax 之前我需要了解什么?

node.js - Mongoose 从另一个字段的 setter 更新依赖字段?