每MDN Forwarded
header 可以有重复值:
转发:for=192.0.2.43,for=198.51.100.17
转发:for=192.0.2.43, for="[2001:db8:cafe::17]"
但是每当我使用npm cookie
(link)为了解析 header 值,我得到了一个不正确的值:
const cookie = require('cookie');
...
...
console.log(cookie.parse(req.headers.forwarded));
输入:
header 键:转发
header 值:for=192.0.2.43,for=198.51.100.17
输出:
这会打印值{ for: '192.0.2.43, for=198.51.100.17' }
。
但正确的输出应该是一个数组: { for: ["192.0.2.43", "198.51.100.17"] }
我尝试了多个 cookie 解析库,但它们似乎无法正确解析重复值。那么我应该使用哪个库?
最佳答案
我最终使用了 foreach 循环来迭代标题,但我仍然困惑为什么这是必要的。
if (req.headers.forwarded) {
for (let current of req.headers.forwarded.split(",")) {
if (cookie.parse(current)["for"]) {
ip = ip + cookie.parse(current)["for"] + ", "
}
}
if (ip.endsWith(", ")) {
ip = ip.substring(0, ip.length -2);
}
}
关于node.js - NPM Cookie 库无法正确解析具有重复值的转发 HTTP header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52786422/