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

Categories

0 votes
1.1k 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

62 comments

56.5k users

...