让快递服务器接受CORS请求
我有我的快递服务器运行在http:// localhost:3000 (我称之为networking服务器)我有另一个应用程序运行在本地主机:8100(我称之为“应用程序”)
当我的应用程序调用Web服务器时,我收到消息:
"XMLHTTPReqeust cannot load http://localhost:3000/auth/facebook. Response to preflight request doesn't pass access control check. A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' when the credentials flag is true. Origin 'http://localhost:81000' is therefore not allowed acecss"
此消息显示在浏览器控制台中。
我在我的节点Web服务器的中间件中设置了以下选项
res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Methods', 'GET,PUT, POST,DELETE');
在阅读了一些stackoverfow问题之后,我还添加了以下内容:
res.header('Access-Control-Allow-Origin', 'http://localhost:8100');
但是这并不能解决问题。
我个人比较喜欢cors模块。 代码非常简单:
var whitelist = [ 'http://0.0.0.0:3000', ]; var corsOptions = { origin: function(origin, callback){ var originIsWhitelisted = whitelist.indexOf(origin) !== -1; callback(null, originIsWhitelisted); }, credentials: true }; app.use(cors(corsOptions));
您还需要在标题中允许使用OPTIONS
方法。
我有这个Cors中间件:
module.exports = function (req, res, next) { // CORS headers res.header("Access-Control-Allow-Origin", "YOUR_URL"); // restrict it to the required domain res.header("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,OPTIONS"); // Set custom headers for CORS res.header("Access-Control-Allow-Headers", "Content-type,Accept,X-Custom-Header"); if (req.method === "OPTIONS") { return res.status(200).end(); } return next(); };
PS。 你得到的错误是由于跨源请求如何工作的事实。 长话短说,浏览器可能会首先发送一个OPTIONS
方法,以获得允许的来源,标题和方法。 所以对于这个请求,你应该只返回Access-Control-*
头。 如果pre-flight
顺利,浏览器将继续原始请求。
你可以在这里find更多的信息。
我用cors来实现它,非常简单
var cors=require('cors');
app.use(cors({origin:true,credentials: true}));
显然Cors模块没有工作。
使用上面给出的提示,我使用了下面的代码:
if (req.method === "OPTIONS") { res.header('Access-Control-Allow-Origin', req.headers.origin); } else { res.header('Access-Control-Allow-Origin', '*'); }
这个伎俩。
遇到了同样的问题,偶然发现了一个小时左右,解决scheme实际上很简单,只需启用CORS进行预检操作
app.options('*', cors()); // include before other routes