我对 Node.js 完全陌生,只是想运行一些示例代码,但是我不断遇到 CORS 问题。
服务器.js
var http = require('http');
var io = require('socket.io');
server = http.createServer(function(req, res){
});
server.listen(8080);
// socket.io
var socket = io.listen(server, { origins: '*:*' });
// Enables CORS
var enableCORS = function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content- Length, X-Requested-With');
// intercept OPTIONS method
if ('OPTIONS' == req.method) {
res.send(200);
}
else {
next();
}
};
// enable CORS!
socket.use(enableCORS);
//--------------
socket.on('connection', function(client){
client.on('message', function(msg){
socket.broadcast(msg);
})
});
客户端代码:
var socket = io.connect('127.0.0.7:8080');
socket.on('message', function(msg){
alert(msg);
console.log(msg);
});
我尝试为 node.js 安装 CORS 模块,但我不断在 Firefox 调试器中收到消息,但我仍然不断收到此消息:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://8080/socket.io/1/?t=1400151675528. This can be fixed by moving the resource to the same domain or enabling CORS.
ReferenceError: socket is not defined client2.html:8
ReferenceError: socket is not defined
最佳答案
仅在目标服务器上设置 CORS header 是不够的。您还需要为为您的客户端 HTML 文件提供服务的 Web 服务器设置适当的 header 。
由于您没有提及如何提供客户端文件,因此我无法为您发布正确的解决方案。但如果您使用 Apache httpd,您可以将以下内容放入配置或 .htaccess
中:
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, x-http-method-override, content-type"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"
关于javascript - CORS Node.js 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23676088/