Search code examples
javascriptexpressaxioscorspreflight

Being blocked by CORS: Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response


I am getting the error

Access to XMLHttpRequest at 'http://localhost:4000/api/investments' from origin 'http://localhost:5000' has been blocked by CORS policy: Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response.

Whenever I try to post some data to my api using the following axios command

  const [login, setLogin] = useState(
    localStorage.getItem('userInfo')
      ? JSON.parse(localStorage.getItem('userInfo'))
      : null
  );
const config = {
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${login.token}`,
      },
    };
 await axios
      .post(`${Config.SERVER_ADDRESS}/api/investments`, investmentObj, config)
      .then((response) => {
        console.log(investmentObj);
        notify(`${response.data.name} investimento cadastrado com Sucesso`);
        history.push(`/app/investment/${response.data._id}`);
      })
      .catch((err) => {
        console.log(err);

        notify(err.response.data, 'danger');
      });

I don't know what to do, since I am using the following middleware:

app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', '*');
  res.header('Access-Control-Allow-Credentials', true);
  res.header(
    'Access-Control-Allow-Headers',
    'Origin, Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers'
  );

  app.use(cors());
  next();
});

I think that my issue is related to the Authorization in the headers, since my other api calls are working... Hopefully any of you guys will help me with such preflight request


Solution

  • I just added the following code app.options('*', cors()); and now it is everything working... Check that out on the documentation from CORS npm https://www.npmjs.com/package/cors#enabling-cors-pre-flight

    app.use((req, res, next) => {
      res.header('Access-Control-Allow-Origin', '*');
      res.header('Access-Control-Allow-Methods', '*');
      res.header('Access-Control-Allow-Credentials', true);
      res.header(
        'Access-Control-Allow-Headers',
        'Origin, Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers'
      );
    
      app.use(cors({ credentials: true, origin: true }));
      next();
    });
    app.options('*', cors());