首页 > 解决方案 > 正文解析器无法/不解析来自 GET 请求的 urlencoded 参数

问题描述

我正在使用 Nodejs 服务器创建一个 Web 平台。我正在尝试检索从我前面发送的 urlencoded 数据,但无法做到。

我如何发送 GET 请求:

xhr.open("GET", address + "?limit=1&offset=1",true);
xhr.setRequestHeader('Authorization', 'Bearer ' + token);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(null);
xhr.addEventListener("readystatechange", processRequest, false);

在服务器端:

const bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: true });

app.get('/guid_list', urlencodedParser, function (req, res) {
  console.log(req.body.limit);
  console.log(req.body.offset);
  var headerjwt = HeaderGetJWT(req);
...
}

我在检索我发送的 jwt 令牌时没有问题,但对于 urlencoded 参数总是未定义。我想知道是否应该使用多部分内容类型,因为我同时发送令牌和 urlencoded 数据?在这种情况下可能是“multer”模块,因为 body-Parser 不支持该内容类型。

标签: node.jsurlencodebody-parser

解决方案


我建议按如下方式访问 Node.js 中的参数(因为它们是作为查询参数传递的):

app.get('/guid_list', parser, function (req, res) {
    console.log("req.query.limit:", req.query.limit);
    console.log("req.query.offset:", req.query.offset);

});

或者只记录所有参数:

app.get('/guid_list', parser, function (req, res) {
    console.log("req.query:", req.query);
});

推荐阅读