Express - 无法从请求 header 中检索 api-key

Express - Cannot retrieve api-key from request header

我正在使用 Rest 和 fetch() API 在浏览器中使用 POST 数据和 x-api-key header 进行授权。 我用 Postman 和 curl 测试了 API,它工作得很好:

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

但是,它不适用于提取 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
  });

x-api-key header 也没有出现在 req.headers object 中。 请帮助

我看到了一个问题,不确定是不是这个问题的原因,但你忘记了你的 , 在你的 fetch headers 中,也许在添加 , 之后试试?

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