【问题标题】:Express - Cannot retrieve api-key from request headerExpress - 无法从请求标头中检索 api-key
【发布时间】:2022-01-21 12:30:45
【问题描述】:

我正在浏览器中使用 Rest 和 fetch() API 来发布带有 x-api-key 标头的数据以进行授权。 我用 Postman 和 curl 测试了 API,它工作得很好:

curl --header "X-API-KEY: my-api-key" -d "my-request-body" -X POST http://localhost:8081/submit

但是,它不适用于 fetch api。在 Chrome 上:

  const response = await fetch(url, {
    method: 'POST',
    mode: 'no-cors',
    cache: 'no-cache',
    headers: {
      'x-api-key': 'my-api-key',
      'Accept': 'text/plain',
      'Content-Type': 'text/plain'
    },
    redirect: 'follow',
    referrerPolicy: 'no-referrer',
    body: 'my-request-body'
  });

我无法从请求中检索 API 密钥。在我的快递中,路由器处理程序:

router.post('/submit', cors(), async (req,res, next) => {
  const apiKey = req.header('x-api-key');
  console.log(apiKey) // THIS GIVES undefined
  });

req.headers 对象中也没有 x-api-key 标头。请帮助

【问题讨论】:

    标签: node.js rest express fetch


    【解决方案1】:

    我看到一个问题,不确定是否是导致它的原因,但您在提取标头中忘记了您的 ,,也许在添加 , 后尝试?

    【讨论】:

    • 不,这不是原因。我编辑了问题
    【解决方案2】:

    好的。经过一段时间的努力,我发现了导致它的问题...... mode: 'no-cors' 一直是造成它的原因。只需将其设置为 mode: 'cors' 就可以了,出于某种原因

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-05-16
      • 2014-03-30
      • 1970-01-01
      • 1970-01-01
      • 2019-04-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多