axios autohorization headers / CORS error

Viewed 10986

I'm using react with axios to fetch some information. I'm sending JWT token to auth user and im geting response in console browser

"Access to XMLHttpRequest at 'https://beer-tonight.herokuapp.com/beer/getBeerStatus' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response."

This is my code:

componentWillMount(){

    let token = localStorage.getItem('token');


    axios.get('https://beer-tonight.herokuapp.com/beer/getBeerStatus', {headers: {Authorization : 'Bearer ' + token}}).then(
    result => {
        console.log('yey');
    });
}

Error:

enter image description here

When I am using POSTMAN I am getting proper answer.

Postman input:

enter image description here

p.s. i already added :

app.use((req, res,next)=>{
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorisation');
next();
2 Answers

You've written Authorisation:

res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorisation');

But the header is Authorization as you have used with axios, try changing that and seeing if it works then,

I believe the cors error that you are receiving is from your node.js api. (https://beer-tonight.herokuapp.com/beer/getBeerStatus)

Since the host do are not the same origin (beer-tonight.herokuapp.com does not match with localhost), you need to enable cors for your node.js server.

If you are using express:

const express = require('express');
const cors = require('cors');
const app = express();

app.use(cors());

// ...

Source: here

Hapi.js:

server.connection({ routes: { cors: true } })

Source: here

Once you have CORS enabled, everything should work smoothly. More on CORS

Related