简体   繁体   English

CORS Node.js服务器

[英]CORS Node.js server

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. 我对Node.js完全陌生,只是想让一些示例代码运行,但是我一直遇到CORS问题。

Server.js 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: 我尝试为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

It is not enough to set CORS headers on the target server only. 仅在目标服务器上设置CORS标头是不够的。 You also need to set the appropriate headers for the web server that serves your client-side HTML file . 您还需要为提供客户端HTML文件的Web服务器设置适当的标头。

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 : 但是,如果您使用的是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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM