Térence
Térence

Reputation: 61

Axios Authorization headers undefined when using Vue.JS and Node.JS

I got a problem when settings authorization headers to my axios instance.

Here is the code in my Vue.JS app running on http://localhost:8080 :

axios.defaults.headers.common['Authorization'] = 'Bearer ' + token

axios.get(`/users/email/${myemail}`).then(response => {
   var user = response.data.result[0]
   ...
});

And here is a sample of my Node.JS server code running on http://localhost:3000 :

// Add headers
app.use((req, res, next) => {  
  res.setHeader('Access-Control-Allow-Origin', '*');

  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

  res.setHeader('Access-Control-Allow-Headers', 'Content-type, Accept, X-Access-Token, X-Key, Authorization');

  res.setHeader('Access-Control-Allow-Credentials', true);

  next();
});

And :

app.use((req, res, next) => {
  var token = req.headers['authorization'];
  if (token) {
    jwt.verify(token, "mysecret", (err, decod) => {
      if (err) {
        res.status(403).send({message: "Access forbidden, wrong token."});
      } else {
        req.decoded = decod;
        next();
      }
    });
  } else {
    res.status(403).send({message: "Access forbidden, no token provided."});
  }
});

The req.headers['authorization'] is always undefined... But when I execute the get request via Postman, the Authorization header is properly set, and I can get the token on my Node.JS server.

I don't understand where is my mistake... Thank's a lot for your help !

Upvotes: 1

Views: 5568

Answers (1)

André Lorenz
André Lorenz

Reputation: 46

Your axios header key is "Authorization", but in node you get with "authorization".

The javascript object key is case-sensitive :D

Upvotes: 3

Related Questions