will-hart
will-hart

Reputation: 3831

fetch() sends lower case header keys

I'm writing an HTTP API library for use in Atom Electron. It is based on fetch. The server is outside of my control, but is written in PHP and I can see it checks headers in a case-sensitive fashion.

My code is something like:

const headers = new Headers();
headers.append('Authorization', `Bearer ${key}`);

const init = {
    method: 'GET',
    headers: headers 
} 

const req = new Request(baseUrl + '/items?format=json');
return fetch(req, init);

The request is rejected with a 403 FORBIDDEN error. When I look at the request in the Electron Newtork panel, the request headers are present but Authorization has become authorization.

I know fetch() is just following the HTTP Standard, but is there a simple way to get fetch() to send the headers as I supply them?

Upvotes: 52

Views: 14259

Answers (3)

paddycorr
paddycorr

Reputation: 111

Currently fetch will toLowercase() all headers when used with the Headers constructor. (there is some discussion here https://github.com/whatwg/fetch/issues/304 about optional disabling).

For now you may need to use http://api.jquery.com/jquery.ajax/ with the header option.

Upvotes: 10

p.boiko
p.boiko

Reputation: 1126

Firefox v110, Chromium v108:

Creating headers with constructor new Headers() lowers the case, but providing request headers as plain object sends proper capital Athorization: Bearer

So instead of

fetch('api/end-point', {
  headers: new Headers(...)
})

I do this:

fetch('api/end-point', {
  headers: {
    ...{other headers},
    Authorization: `Bearer ${token}`,
  }
})

Not tested in other environments

Upvotes: 1

Sten Muchow
Sten Muchow

Reputation: 6711

Using fetch myself and doing a similar thing we do as follows...

const GLOBALS = require('./Globals');
const HEADERS = {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
};
const resourceURL = '/some/endpoint'
const body = '';

var request = new Request(`${GLOBALS.API_ENDPOINT}${resourceURL}`, {
                        method: 'GET',
                        headers: new Headers(Object.assign(HEADERS, {'Authorization': `JWT ${token}`})),
                        body: body ? JSON.stringify(body) : null
                    }); 

return fetch(request)
    .then(res => consume)

Take is as pseudo pseudo code as there are some functional parameters we pass in that are evaluated in the template literal.

Upvotes: -3

Related Questions