简体   繁体   中英

How to solve node.JS passport oauth2 cors error

I am trying to configure node passport oauth2 login.

If call the get url directly from the browswer, everyhting works perfectly.

I am trying to set up the login using react client as frontend.

react axios api call

 const res = await Axios.get(http://locahost:5000/login`)

node.js express

app.use(cors({
  'allowedHeaders': ['sessionId', 'Content-Type', 'authorization'],
  'exposedHeaders': ['sessionId','authorization'],
  // 'origin': true,
  // 'Access-Control-Allow-Origin': 'http://localhost:8080',
  'methods': 'GET,HEAD,PUT,PATCH,POST,DELETE, OPTIONS',
  'preflightContinue': false
}));

app.use(bodyParser.json({ limit: "50mb", extended: true }));

app.get('/npt/login', passport.authenticate('oauth2'));

This is the error I get

Access to XMLHttpRequest at 'https://...' (redirected from 'http://localhost:5000/npt/login') from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Do I need to set the headers in the client app?

UPDATE: I am trying to use this configuration using Azure App Registration.

I have updated the express CORS settings.

UPDATE2: I have managed to solve the issue running the frontend on the same origin as the nodeJS express server. This is the example I have followed: https://github.com/cicorias/react-azuread-passport

if you run react side via CRA

you can add proxy in package.json file

like this:

"proxy": "http://yourTarget.com",

and call http requests from

http://localhost:3000

notice : when you change package.json file you must reset npm start command to see the changes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM