跨域预检OPTIONS请求正常,但后续GET/POST遭CORS拦截问题排查
跨域CORS问题排查与解决
我遇到了跨域资源共享(CORS)问题:预检请求的OPTIONS方法可正常执行,但之后前端与后端之间的跨域GET/POST请求仍被CORS拦截。以下是我的后端CORS配置代码:
const corsWhitelist = ["http://localhost:3000", "http://localhost:5000", "https://www.myfrontendwebsite.com"]; const corsOptions = { origin: (originReq, callback) => { // Access-Control-Allow-Origin loggers.info("INSIDE CORSOPTIONS!!!! originReq!YES!!!!!"); loggers.info(originReq); // the origin website name if (corsWhitelist.indexOf(originReq)!== -1) { callback(null, true); // reflect (enable) the requested origin in the CORS response } else { callback(null, false); // disable CORS for this request } }, // origin: ["http://localhost:3000", "http://localhost:5000", FRONTEND], credentials: true, //Access-Control-Allow-Credentials: true optionSuccessStatus: 200, allowHeaders: ["Access-Control-Allow-Origin", "Access-Control-Allow-Headers", "Access-Control-Allow-Methods", "X-Requested-With", "Content-Type", "Accept"], methods: ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"], }; app.options("*", cors(corsOptions)); app.use(cors(corsOptions));
在主机日志中可见OPTIONS方法执行成功,但后续GET请求被拦截,错误信息如下:
Access to fetch at 'https://www.backendwebserver.com/api/v2/login' from origin 'https://www.myfrontendwebsite.com' 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
解决说明
- 修正两处配置项拼写错误:
- 将
optionSuccessStatus改为optionsSuccessStatus - 将
allowHeaders改为allowedHeaders
- 将
- 核心修复点:origin回调的处理逻辑错误,将
callback(null, true)改为callback(null, { origin: true })后,问题彻底解决。
内容的提问来源于stack exchange,提问作者Mohamed
相关产品推荐
相关产品推荐

