向 Aurelia Fetch 请求添加自定义 header

Add a custom header to Aurelia Fetch request

我正在尝试使用 Aurelia 的 Fetch Client 将自定义 header 添加到所有 GET 和 POST 请求。以下代码(在 app.js 构造函数中)用于设置基础 URL 但 header 没有按我想要的方式工作:

constructor(httpClient) {
  // set up httpClient
  httpClient.configure(config => {
    config
      .withBaseUrl(localsettings.api)
      .withDefaults({
        credentials: 'include',
        headers: {
          'my_appkey': 'f2eabc5e7de-a4cdc857e'
        }
      })
  });
  this.httpClient = httpClient;
}

用法:

this.httpClient.fetch(suburl, {
    credentials: 'include'
  }).then(response => { ... });

通过Chrome的开发工具,我可以看到 "my_appkey" header 存在但是它没有被创建,因为它是自己的 header 并且它的值不是可见:

请求Headers:

OPTIONS /index.php/api/v1/keys HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Access-Control-Request-Method: GET
Origin: http://localhost:9000
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36
Access-Control-Request-Headers: my_appkey
Accept: */*
Referer: http://localhost:9000/
Accept-Encoding: gzip, deflate, sdch, br
Accept-Language: en-US,en;q=0.8,es-419;q=0.6,es;q=0.4

我做错了什么?为什么我的习惯 header 被移动到 Access-Control-Request-Headers

在请求中添加 my_appkey header 会触发浏览器首先执行 a CORS preflight OPTIONS request,然后再尝试实际的 GET/POST 请求使.

OPTIONS /index.php/api/v1/keys HTTP/1.1
^^^^^^^

作为预检 OPTIONS 的一部分,浏览器会发送一个 Access-Control-Request-Headers header ,其值包括您通过代码添加到请求中的 header 的名称。

The Access-Control-Request-Headers request header is used when issuing a preflight request to let the server know which HTTP headers will be used when the actual request is made.

所以您所看到的都是预期的行为。

并且为了让浏览器认为预检 OPTIONS 请求成功,向其发出请求的服务器必须发送具有 Access-Control-Allow-Headers response header 的响应,其值还包括“my_appkey”。如果没有,那么浏览器就停在那里,永远不会继续发送您想要发出的实际 GET/POST 请求。