Difficulties with Axios - Cors setup in React - Flask project

38 Views Asked by At

im facing some problems while setting up the authentication functionality of my react - flask application.

This is what my headers look like and what the error says.

I am running server sided sessions that i am using redis for. After the POST request i want to return a cookie in the future, because of that i need Credentials to be true.

Thats my frontend:

httpClient

post request

And the backend:

Both versions dont work.

Axios is installed and flask-cors as well.

I already spent a view hours in trying to solve this problem mostly in vary with the post() headers and/or the CORS() settings but this is still what gave me the most promising result.

I also did read a lot of posts about this topic but couldn't find a solution.

Thank you very much and any advice will be appreciated very much.

2

There are 2 best solutions below

0
prakhar maurya On

you need to add CORS preflight by OPTIONS method reply in backend other than access control headers.

res.setHeader('Access-Control-Allow-Origin', '*',);
res.setHeader('Access-Control-Allow-Headers', 'Content-Type,Mode,access-control-allow-origin');
res.setHeader('Access-Control-Allow-Methods', 'GET,POST,PUT,PATCH,DELETE');
res.setHeader('Access-Control-Allow-Credentials', true);

if (req.method === 'OPTIONS') {
  return res.end()
}
0
moon548834 On

My experience is that

you should add a reverse proxy in the frontend, even though the flask is configured.

I got a similar problem and the cors problem comes from browser, it seems your frontend is in localhost:3000, and the backend is in localhost:5000, you send the request directly to the backend like localhost:5000/user/login in your error picture which is the cause.

you should send all the request to a temp endpoint like localhost:5000/api/xxx, then the proxy send the request to localhost:3000/xxx, that's the reverse proxy thing.

I am using webpack, for local development, this is my configure, and this do the exactly thing I have mentioned

devServer: {
      static: './dist',
      port: 7789,
      historyApiFallback: true,
      proxy: {
        '/api': {
          target: env.BACKEND_URL,
          pathRewrite: {
            '^/api': '',
          },
        },
        secure: false,
      },
    },

I believe other bundle tools like vite should have similar configurations

Before:

localhost:3000 -> localhost:5000

Now:

localhost:3000 -> localhost:3000/api(reverse proxy) -> localhost:5000