Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
18
rated 0 times [  21] [ 3]  / answers: 1 / hits: 91315  / 7 Years ago, wed, august 9, 2017, 12:00:00

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.


More From » http

 Answers
68

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.


[#56817] Monday, August 7, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kenandwightb

Total Points: 241
Total Questions: 95
Total Answers: 111

Location: Jersey
Member since Fri, Oct 1, 2021
3 Years ago
;