2

I am trying to add a custom header, X-Query-Key, to a HTTP request using Fetch API or request but when I add this to the header of the request it appears to fail at setting the headers and the Request Method is set to OPTIONS for some reason.

When I remove the header it goes back to being GET as it should do.

Sample code looks like below:

 const options = { url: url, headers: { 'Accept': 'application/json', 'X-Query-Key': '123456' //Adding this breaks the request } }; return request(options, (err, res, body) => { console.log(body); }); 
1
  • 2
    Sounds like CORS. Commented Oct 4, 2016 at 23:43

2 Answers 2

1

Try this:

const headers = new Headers({ "Accept": "application/json", "X-Query-Key": "123456", }); const options = { url: url, headers: headers }; return request(options, (err, res, body) => { console.log(body); }); 

If that does not solve the issue, it may be related to CORS.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks - This worked, guess I was missing the Headers - Now I get the CORS issue which is my next problem :D
I think it's because you have to invoke the constructor in order to create your own headers. Hey, at least the fetch API makes CORS much simpler to handle. The real snag with the new fetch API is that a fetch request cannot be aborted. fetch has its uses for ServiceWorkers, but in practice I've found myself using XHR2 everywhere still.
1

Custom headers on cross-origin requests must be supported by the server from which the resource is requested. The server in this example would need to be configured to accept the X-Custom-Header header in order for the fetch to succeed. When a custom header is set, the browser performs a preflight check. This means that the browser first sends an OPTIONS request to the server to determine what HTTP methods and headers are allowed by the server. If the server is configured to accept the method and headers of the original request, then it is sent. Otherwise, an error is thrown.

So you will have 2 requests if use custom headers, first one with method OPTIONS to check if server allows custom headers and after that if the server response is 200 OK and allows your originary request the second one will be send

Working with the Fetch API

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.