-1

I am using axios to call api and bearer token way for authorization, my code:

export default axios.create({
    baseURL,
    headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer  ${localStorage.getItem('token')}`
    }
});

in UserRepository.js, the Repository is imported and the api be called by:

loadUsers() {
    return Repository.get(`${users}`);
}

Then the error is "unauthorization", but when I update the header:

export default axios.create({
    baseURL,
    headers: {
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Methods': 'GET, PUT, POST, DELETE, OPTIONS',
        'Content-Type': 'application/json',
        'Authorization': `Bearer  ${localStorage.getItem('token')}`
    }
});

The error is: Access to XMLHttpRequest at 'http://example.com/users' from origin 'http://localhost:8080' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response.

2 Answers2

1

The error you are getting is because the server is responsible for reporting the allowed origins. If your server was an express server you would use this piece of code to resolve this error:

`

app.use(function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
});
`

see here for more info.

mtho
  • 21
  • 3
-2

This part of the code should be in your api not not the client. It is part of the response headers.

'Access-Control-Allow-Origin': '*',
  'Content-Type': 'application/json',
Saif Kamaal
  • 186
  • 8
  • 1
    Nothing wrong with `Content-type` as a request header (for POST, PUT, etc requests) – Phil Jun 25 '19 at 05:42