سؤال

I am totally new to Node.js and am just trying to get some example code running however I keep running into issues with CORS.

Server.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);
  })
}); 

client code:

var socket = io.connect('127.0.0.7:8080');
socket.on('message', function(msg){
alert(msg);
console.log(msg);
});

I tried installing the CORS module for node.js but I keep getting messages in firefox debugger, but I still keep getting this:

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
هل كانت مفيدة؟

المحلول

It is not enough to set CORS headers on the target server only. You also need to set the appropriate headers for the web server that serves your client-side HTML file.

Since you did not mention how you serve your client-side files, I can not post the right solution for you. But if you are using Apache httpd, you could put the following in the configuration or .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"
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top