node.js 将自定义标头添加到“请求”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38332492/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Add custom headers to 'request'
提问by Ilja
I am proxying my api via following setup in my express config
我通过在我的快速配置中进行以下设置来代理我的 api
// Proxy api calls
app.use('/api', function (req, res) {
let url = config.API_HOST + req.url
req.pipe(request(url)).pipe(res)
})
config.API_HOSTin here resolves to my api url and req.urlis some endpoint i.e. /usersI tried following documentation on npm for requestand set up my headers like so
config.API_HOST在这里解析为我的 api url 并且req.url是某个端点,即/users我尝试按照 npm 上的文档进行请求并像这样设置我的标头
// Proxy api calls
app.use('/api', function (req, res) {
let options = {
url: config.API_HOST + req.url,
options: { 'mycustomheader': 'test' }
}
req.pipe(request(options)).pipe(res)
})
But I am not able to see my custom headers in chrome dev tools under Network.
但是我无法在网络下的 chrome 开发工具中看到我的自定义标头。
回答by Ilja
Was able to achieve it this way
能够以这种方式实现它
app.use('/api', function (req, res) {
let url = config.API_HOST + req.ur
req.headers['someHeader'] = 'someValue'
req.pipe(request(url)).pipe(res)
})
回答by kheengz
for some weird reasons req.setHeader('someHeader', 'somValue')didn't work for me.
由于一些奇怪的原因req.setHeader('someHeader', 'somValue')对我不起作用。
but req.headers['someHeader'] = 'someValue'this worked
但这req.headers['someHeader'] = 'someValue'有效

