Add a custom header to Aurelia Fetch request

Asked By: Anonymous

I’m trying to use Aurelia’s Fetch Client to add a custom header to all GET and POST request. The following code (in app.js constructor) works to set the base URL but the headers are not working the way I want:

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

Usage:

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

Through Chrome’s development tools, I can see that the “my_appkey” header exists but it’s not being created as it’s own header and its value is not visible:

Request 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

What am I doing wrong? Why is my custom header being moved into Access-Control-Request-Headers?


Solution

Answered By: Anonymous

Adding the my_appkey header to the request triggers the browser to first perform a CORS preflight OPTIONS request before attempting the actual GET/POST request you want to make.

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

As part of that preflight OPTIONS, the browser sends an Access-Control-Request-Headers header whose value includes the names of headers you’ve added to the request from your code.

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.

So what you’re seeing is all expected behavior.

And in order for the browser to consider that preflight OPTIONS request a success, the server the request is made to must send a response that has an Access-Control-Allow-Headers response header whose value also includes “my_appkey“. If it does not, then the browser stops right there and never proceeds to send the actual GET/POST request you want to make.


Windows 10 Kaufen Windows 10 Pro Office 2019 Kaufen Office 365 Lizenz Windows 10 Home Lizenz Office 2019 Home Business Kaufen windows office 365 satın al follower kaufen instagram follower kaufen porno