CORS in Express works on Safari but not on Chrome

时间:2018-08-22 13:52:41

标签: node.js reactjs express cors

I have an Express application running on AWS ElasticBeanstalk, for which I have enabled CORS by doing below in my entry point:

app.use(cors());

I can do a simple POST request to an endpoint in my server with Postman or in my React app on Safari, for logging in. I cannot do it on Google Chrome, unfortunately. This is what I get on console:

OPTIONS http://**.eu-central-1.elasticbeanstalk.com/signin 0 ()

On network tab of developer tools, I have this:

Error on network tab

I do the API request in React as following:

const customHeader = () => ({
  'Content-Type': 'application/json',
  'Access-Control-Allow-Origin':'*',
  Accept: 'application/json',
  Authorization: 'Bearer ' + localStorage.getItem('id_token') || undefined,
});

const base = (method, url, data = {}) => {
  return fetch(`${jwtConfig.fetchUrl}${url}`, {
    method,
    headers: customHeader(),
    body: JSON.stringify(data),
  })
    .then(response => response.json())
    .then(res => res)
    .catch(error => ({ error: 'Server Error' }));
};

const SuperFetch = {};
['get', 'post', 'put', 'delete'].forEach(method => {
  SuperFetch[method] = base.bind(null, method);
});
export default SuperFetch;

And calling:

await SuperFetch.post('signin', userInfo)

The fact that it is working on Postman and Safari leads me to believe that it has something to do with Google Chrome. I also have this extension enabled but it does not solve the problem.

1 个答案:

答案 0 :(得分:0)

Add this flag as well:

Access-Control-Allow-Headers: Content-Type,Authorization