我正在尝试通过XMLHttpRequest传递params并获取'undefined' -
客户:
var xj = new XMLHttpRequest();
var params = JSON.stringify({
PreviousTab: "cnn.com",
CurrentTab: "bbc.com"
});
xj.open("GET", "http://localhost:8080/api/traceTabs", true);
xj.setRequestHeader("Content-Type", "application/json");
xj.setRequestHeader ("Accept", "application/json");
xj.send(params);
服务器(Node.js):
app.get('/api/traceTabs', function (req, res) {
console.log('change url from ' + req.body.PreviousTab +
' to ' + req.body.CurrentTab); // return 'undefined'
});
server.js配置(Node.js):
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var port = process.env.PORT || 8080;
app.use(bodyParser.json());
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(methodOverride('X-HTTP-Method-Override'));
app.use(express.static(__dirname + '/public'));
require('./app/routes')(app);
app.listen(port);
console.log('Listen to port ' + port);
exports = module.exports = app;
我试图获得params的所有选项都返回'undefined':
req.body.PreviousTab / req.param('PreviousTab')等等。
有人可以帮忙吗?
答案 0 :(得分:1)
如上所述,GET或HEAD请求不能有正文。 如果您的数据很大,您应该转到POST请求。
但是,如果要使用的参数与示例中的参数一样短,则应use query strings:
var url = "bla.php";
var params = "somevariable=somevalue&anothervariable=anothervalue";
var http = new XMLHttpRequest();
http.open("GET", url+"?"+params, true);
http.send(null);
在节点方面,假设您使用express,您可以使用:
读取变量var somevariable = req.query.somevariable;
var anothervariable = req.query.anothervariable;
答案 1 :(得分:0)
来自XMLHttlRequest.send()
文档:
... If the request method is GET OR HEAD,
the argument is ignored and the request body is set to null.
将您的发送方式更改为POST。