在“请求”中添加自定义标头

26
我正在通过我的Express配置进行API代理,如下所示。

我正在通过我的Express配置进行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_HOST在这里解析为我的API网址,req.url 是一些端点,例如 /users。我尝试遵循npm文档中关于request的说明,并像下面那样设置了我的标头。

  // 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)
  })

但是我无法在Chrome开发者工具的网络选项卡中看到我的定制请求头。

1个回答

42

用这种方法成功地实现了它

  app.use('/api', function (req, res) {
    let url = config.API_HOST + req.ur
    req.headers['someHeader'] = 'someValue'
    req.pipe(request(url)).pipe(res)
  })

当您向 /api 发送 get 请求时,它将被发送一个名为 'someHeader' 的头部,其值为 'someValue'? - Roger Peixoto
这对我也起作用。 我尝试使用res.setHeader设置头部,但没有成功。 req ['token] ="some_token"可以工作。 我在想是否安全.. - Stephan Bakkelund Valois
请小心,我刚注意到已经包含在接收请求中的标头可以通过req.get("abc")读取,并且对于通过req.headers.abc = 'xyz'添加的标头将返回undefined。另一方面,const x = req.headers.abc将返回通过req.headers.abc = 'xyz'创建的标头的值,而对于实际接收到的请求中包含的标头将返回undefined - Mon

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接