Reputation: 3392
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);
});
Upvotes: 2
Views: 6312
Reputation: 136
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
Upvotes: 1
Reputation: 1903
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.
Upvotes: 1