fetch() does not send headers?

Rasto picture Rasto · Aug 9, 2017 · Viewed 42k times · Source

I am sending POST request like this from browser:

fetch(serverEndpoint, {
    method: 'POST',
    mode: 'no-cors', // this is to prevent browser from sending 'OPTIONS' method request first
    redirect: 'follow',
    headers: new Headers({
            'Content-Type': 'text/plain',
            'X-My-Custom-Header': 'value-v',
            'Authorization': 'Bearer ' + token,
    }),
    body: companyName
})

By the time the request reaches my back-end it does not contain X-My-Custom-Header nor Authorization header.

My back-end is Google Cloud function for Firebase (basically just Node.js endpoint) that looks like this:

exports.createCompany = functions.https.onRequest((req, res) => {
    let headers = ['Headers: ']
    for (let header in req.headers) {
        headers.push(`${header} : ${req.headers[header]}`)
    }
    console.log(headers)
    ...
}

The console log of that Google Cloud for Firebase function does not contain any X-My-Custom-Header nor Authorization header.

What is wrong?


Edit 1

So using dev tools in Chrome a checked that neither X-My-Custom-Header nor Authorization header is send from the browser... The questions now are: Why? How do I fix it?


Edit 2

More information about my app: It's React app. I have disabled service worker. I have tried to create Request and specifically add headers using req.headers.append(). The headers still wouldn't send.

Answer

Vasiliy Faronov picture Vasiliy Faronov · Aug 11, 2017

The same-origin policy restricts the kinds of requests that a Web page can send to resources from another origin.

In the no-cors mode, the browser is limited to sending “simple” requests — those with safelisted methods and safelisted headers only.

To send a cross-origin request with headers like Authorization and X-My-Custom-Header, you have to drop the no-cors mode and support preflight requests (OPTIONS).

The distinction between “simple” and “non-simple” requests is for historical reasons. Web pages could always perform some cross-origin requests through various means (such as creating and submitting a form), so when Web browsers introduced a principled means of sending cross-origin requests (cross-origin resource sharing, or CORS), it was decided that such “simple” requests could be exempt from the preflight OPTIONS check.