2
votes

I have a VueJS application and a ExpressJS server side application. On my server I have the following:

var allowCrossDomain = function(req, res, next) {
    res.header('Access-Control-Allow-Origin', req.headers.origin);
    res.setHeader("Access-Control-Allow-Credentials", "true");
    res.setHeader("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
    next();
}
app.use(allowCrossDomain);

However, I keep getting the following error:

Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response.

I'm sending my request like this:

import axios from 'axios'

export default axios.create({
  baseURL: 'https://example.com',
  timeout: 5000,
  headers: {
    'Authorization': 'Bearer ' + accessToken
  }
})

How can I get around this? I have tried many solutions and read up on this. I have read the below:

1
Is your server responding to the OPTIONS request which is what the browser will send to preflight your request to see if it's allowed? I'd suggest you look at the network tab in the Chrome debugger and see exactly what the browser is sending and what your server is responding with. Usually, you can see the problem more precisely in that info.jfriend00

1 Answers

3
votes

The code in the question apparently isn’t causing the Access-Control-Allow-Headers header to get sent for OPTIONS responses — specifically, for the response to the CORS preflight OPTIONS.

To ensure preflight OPTIONS get handled correctly, consider installing the npm cors package:

npm install cors

And then do something like this:

var express = require('express')
  , cors = require('cors')
  , app = express();
app.options('*', cors()); // preflight OPTIONS; put before other routes

That will handle CORS preflight OPTIONS requests and other CORS aspects without you needing to manually write your own handling from scratch in your application code.

https://www.npmjs.com/package/cors#configuration-option has more details on all the options.