Node.js中Node-static中请求的资源上没有“Access-Control-Allow-Origin”标头

我对node.js很陌生,我不知道如何解决这个问题。 希望您能够帮助我。

我有一个运行在node.js中的服务器,它有node-static和socket.io。 代码如下。

var numClients=0; var static = require('node-static'); //var static = require('express'); var http = require('http'); var file = new(static.Server)(); var app = http.createServer(function (req, res) { res.setHeader('Access-Control-Allow-Origin', 'http://172.26.191.45:8080'); // Request methods you wish to allow res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE'); // Request headers you wish to allow res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type'); // Set to true if you need the website to include cookies in the requests sent // to the API (eg in case you use sessions) res.setHeader('Access-Control-Allow-Credentials', true); file.serve(req, res); }).listen(2013); var io = require('socket.io').listen(app); io.sockets.on('connection', function (socket){ function log(){ var array = [">>> "]; for (var i = 0; i < arguments.length; i++) { array.push(arguments[i]); } socket.emit('log', array); } socket.on('message', function (message) { log('Got message: ', message); socket.broadcast.emit('message', message); // should be room only }); socket.on('create or join', function (room) { numClients=numClients+1; log('Room ' + room + ' has ' + numClients + ' client(s)'); log('Request to create or join room', room); if (numClients == 0){ socket.join(room); socket.emit('created', room); } else if (numClients == 1) { io.sockets.in(room).emit('join', room); socket.join(room); socket.emit('joined', room); } else { // max two clients socket.emit('full', room); } socket.emit('emit(): client ' + socket.id + ' joined room ' + room); socket.broadcast.emit('broadcast(): client ' + socket.id + ' joined room ' + room); }); socket.on('disconnect', function () { numClients=numClients-1; log('Room has ' + numClients + ' client(s)'); }); }); 

我的服务器在localhost:2013运行。 我的网页在localhost:8080。 当我尝试访问服务器时,出现以下错误

 XMLHttpRequest cannot load https://computeengineondemand.appspot.com/turn?username=41784574&key=4080218913. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://172.26.191.45:8080' is therefore not allowed access. 

我知道这是由于CORS。 但是我已经添加了代码行来适当地设置Headers。 当我检查这个错误时,大多数人都会说如何用node.js中的express来改善它,但不是node-static。

有人可以build议我下一步可以做什么,当我从不同的域名访问时,从服务器得到响应。

这个问题可能有几种可能的解释:

说明1:原点设置不正确

更改

 res.setHeader('Access-Control-Allow-Origin', 'http://172.26.191.45:8080'); 

 res.setHeader('Access-Control-Allow-Origin', 'localhost'); 

如果这不起作用,请在服务器端输出请求源,并用此源replace“localhost”。 (我不知道有足够的节点告诉你如何输出原点)。

解释2:标题输出不正确

仔细检查服务器返回的头文件。 你可以通过安装一些允许你查看请求头的浏览器插件来完成。

确保标题是正确的。 这里是你需要设置的列表 (对于PHP,但标题是相同的)。