Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

node.js - Disable CORS in Expres.io for socket.io calls

I try to connect from angular to a Express.io socket, but I have error 404 CORS. How can I solve this?

XMLHttpRequest cannot load http://localhost:3000/socket.io/?EIO=3&transport=polling&t=1447367208172-29. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.

If I load this route directly from browser directly, it works well But from localhost:80 angular to localhot:3000 express.io not works.

In my express.io I disabled the CORS, and it works well for the normal ajax requests, but not for socket.io :

app.use(function(req, res, next) {
            res.header('Access-Control-Allow-Credentials', true);
            res.header('Access-Control-Allow-Origin',      req.headers.origin);
            res.header('Access-Control-Allow-Methods',     'GET,PUT,POST,DELETE');
            res.header('Access-Control-Allow-Headers',     'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept');
            next();

});

My initialization of socket.io in express.io:

app.http().io()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Are you running this angular app in chrome? I imagine its the same way for most browsers but on chrome CORS will not work with localhost: https://code.google.com/p/chromium/issues/detail?id=67743

What I've done to get around this in the past is alter my hosts (if on Windows). You can also use lvh.me instead of localhost if you do not want to alter your hosts file on Windows.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...