React request is being sent without an Authorization header

Viewed 1688

I am trying to pass a bearer token, to the fastify http server, in my headers.

I set the headers inside my request as:

...
const headers = {
  Accept: 'application/json',
  'Content-Type': 'application/json'
}
const token = localStorage.getItem('token')
if (token) {
  headers['Authorization'] = `Bearer ${token}`
}
const newOptions = {
  ...options,
  mode: 'no-cors',
  headers
}
console.log('options:', newOptions)
return fetch(url, newOptions)

My console.log prints:

options: {
  mode: "no-cors", 
  headers: {
    Accept: "application/json",
    Content-Type: "application/json",
    Authorization: "Bearer NQ9xQLmYtq92aT8JHHRd7DGZJ..."
  }
}

From the Chrome network tab, I look at the headers, and Authorization is just not present there. My route handler function is below:

async function user(server, options) {
  server.route({
    method: 'GET',
    url: '/user/:email',
    handler: async (req, res) => {
      const username = req.params.email
      console.log('user email:', username)
      console.log('headers:', req.headers)
      res.send({
        type: 'promoter'
      })
    }
  })
}

When I print headers on the server, it also does not have Authorization, showing:

headers: { host: 'localhost:5000',
  connection: 'keep-alive',
  pragma: 'no-cache',
  'cache-control': 'no-cache',
  accept: 'application/json',
  'sec-fetch-dest': 'empty',
  'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.106 Safari/537.36',
  'sec-fetch-site': 'same-site',
  'sec-fetch-mode': 'no-cors',
  referer: 'http://localhost:3000/admin',
  'accept-encoding': 'gzip, deflate, br',
  'accept-language': 'en-US,en;q=0.9,ru;q=0.8' }

What am I missing?

Another interesting issue is that when I run the request from Postman it shows 200 response code, and fastify prints 200 to the log. However, running from the saga/request with:

  return fetch(url, newOptions)
    .then(checkStatus)
    .then(parseJSON)

I get response.status of 0 instead of 200 inside the request method, while the server log still shows "res":{"statusCode":200}.

2 Answers

I figured out what was the problem.

Apparently, my version of Chrome - Version 80.0.3987.106 (Official Build) (64-bit) and possibly other browsers and older versions of Chrome, as well, strip the authorization header, when it is used in conjunction with the no-cors mode. Enabling CORS and setting the appropriate headers solves the problem.

Related