gpt4 book ai didi

node.js - 使用请求解析查询数组并使用 express 接收

转载 作者:搜寻专家 更新时间:2023-11-01 00:05:08 26 4
gpt4 key购买 nike

我在使用 express 和 request 发送和接收查询参数时遇到问题。

请求方:

const request = require('request');
request({url: 'http://localhost', json: true, qs: {id: [1,2,3,4]}})

Request 向我的服务器发送这样的请求:

http://localhost/?id%5B0%5D=1&id%5B1%5D=2&id%5B2%5D=3&id%5B3%5D=4

然后当我使用 express 收到我的结果时

app.get('/', (req, res, next) => {
console.log(req.query);
})

我有

{id: {0: 1, 1: 2, 2: 3, 3: 4}}

我想拥有

{id: [1,2,3,4]}

如果我使用此 url 手动发送请求,它会起作用

http://localhost/?id=1&id=2&id=3&id=4

所以我不明白错误是来自request witch have issues parsing my array 还是 express having problems parsing my query

最佳答案

这与 url 的编码和解码有关,当您解码不起作用的 url 时,您会得到:

http://localhost/?id[0]=1&id[1]=2&id[2]=3&id[3]=4

程序将它们视为对象的索引。 %5B 等于 [%5D 等于编码语法中的 ]。你无法通过这种链接获得该输出,因为我在后端看到你的代码,因为它们被视为对象的索引。

此 url 有效,因为它们未引用任何索引。

http://localhost/?id=1&id=2&id=3&id=4

您可以对来自 this link. 的网址进行编码和解码

关于node.js - 使用请求解析查询数组并使用 express 接收,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46221140/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com