简体   繁体   中英

How to solve CORS redirection with express js router?

I'm trying to implement OAuth2 authentication. When I try to send Authorization code I get this error:

XMLHttpRequest cannot load link1. Redirect from link1 to link2 has been blocked by CORS policy: Request requires preflight, which is disallowed to follow cross-origin redirect.

My req/rsp looks like this:

General: Request URL:link1 Request Method:OPTIONS Status Code:204 No Content Remote Address:

Response Headers: HTTP/1.1 204 No Content X-Powered-By: Express Access-Control-Allow-Origin: * Access-Control-Allow-Methods: GET,HEAD,PUT,PATCH,POST,DELETE Access-Control-Allow-Headers: content-type, sessionid Date:

Request Headers: OPTIONS /authorize HTTP/1.1 Host: host Connection: keep-alive Access-Control-Request-Method: POST Origin: origin_link User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.76 Safari/537.36 Access-Control-Request-Headers: content-type, sessionid Accept: / Referer: origin_link/dialog Accept-Encoding: gzip, deflate, sdch, br Accept-Language: en-US,en;q=0.8

Maybe you have not configured express to accept CORS request.

In a small project, I had to configure CORS request in an Express application. My code was:

// Enable CORS
app.use((req, res, next) => {
   res.header('Access-Control-Allow-Origin', '*');
   res.header('Access-Control-Allow-Methods', 'GET,POST,DELETE');
   res.header('Access-Control-Allow-Headers', 'Origin, X-Requested With, Content-Type, Accept');
   next();
});

app is a variable corresponding to an Express instance.

Moreover, I did find an npm package to set CORS request to an express app, but I have never used it: https://github.com/expressjs/cors

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