为了解决跨域访问问题,我在后台设置了如下代码:
app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
res.header("X-Powered-By",' 3.2.1')
res.header("Content-Type", "application/json;charset=utf-8");
next();
});
然后在使用socket.io时,浏览器控制台报以下错误:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access. The response had HTTP status code 404.
求大神解惑,万分感谢!
原因已找到,因为后台设置的webserver监听端口和socket.io监听端口一致
处理跨域直接使用cors package,不需要自己再去实现了。
你试试用app.use,socket的请求好像不走route,app.all是route里面的
app.use(function (req, res, next) {
//...
});