【问题标题】:XMLHttpRequest GET params undefined in request nodejs api请求nodejs api中未定义的XMLHttpRequest GET参数
【发布时间】:2018-06-04 04:19:07
【问题描述】:

我正在尝试通过 XMLHttpRequest 传递参数并获得“未定义”-

客户:

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;                         

我尝试获取参数的所有选项都返回“未定义”:

req.body.PreviousTab / req.param('PreviousTab') 等等。

有人可以帮忙吗?

【问题讨论】:

  • 能否添加中间件相关的服务器端代码
  • 您需要 POST 或 PUT 才能发送参数 - 检查您的浏览器开发者工具网络选项卡,您会看到请求中没有发送任何参数
  • 查看 XMLHttpRequest send() 的定义 -> xhr.spec.whatwg.org/#the-send()-method - 更准确地说是我之前的评论,对于 GET/HEAD 请求,发送正文被强制为空 - 所以,PUT/POST 方法是不是您可以使用正文发送的唯一方法 - 但是,它们是最常见的

标签: javascript node.js express xmlhttprequest


【解决方案1】:

来自XMLHttlRequest.send() docs:

... If the request method is GET OR HEAD,
the argument is ignored and the request body is set to null.

将您的发送方式更改为 POST。

【讨论】:

    【解决方案2】:

    如前所述,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;
    

    【讨论】: