javascript Socket.io 请求的资源上不存在“Access-Control-Allow-Origin”标头。因此不允许访问源 'http://localhost'
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28244932/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Socket.io No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access
提问by hgerdin
I'm trying to learn nodejs with socket.io and at the moment I'm using this tutorial by GianlucaGuarini. When entering my client.html file I get the following error. I know what it means and that it′s there for preventing Cross browser scripts but I don′t know how to allow my nodejs script to access the client.html file.
我正在尝试使用 socket.io 学习 nodejs,目前我正在使用GianlucaGuarini 的本教程。输入我的 client.html 文件时,出现以下错误。我知道这意味着什么,它用于防止跨浏览器脚本,但我不知道如何允许我的 nodejs 脚本访问 client.html 文件。
XMLHttpRequest cannot load http://localhost:8000/socket.io/?EIO=3&transport=polling&t=1422653081432-10. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.
Here is a part of my code with socket.
这是我的套接字代码的一部分。
var app = require('http').createServer(handler),
io = require('socket.io').listen(app),
fs = require('fs'),
mysql = require('mysql'),
connectionsArray = [],
connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'database',
port: 3306
}),
POLLING_INTERVAL = 3000,
pollingTimer;
// If there is an error connecting to the database
connection.connect(function(err) {
// connected! (unless `err` is set)
console.log(err);
});
// creating the server ( localhost:8000 )
app.listen(8000);
// on server started we can load our client.html page
function handler(req, res) {
res.writeHead(200, {
/// ...
'Access-Control-Allow-Origin' : '*'
});
fs.readFile(__dirname + '/client.html', function(err, data) {
if (err) {
console.log(err);
res.writeHead(500);
return res.end('Error loading client.html');
}
res.writeHead(200);
res.end(data);
});
}
Does anyone know how I can solve my problem?
有谁知道我该如何解决我的问题?
Kind regard / H
亲切的问候 / H
回答by JerryCauser
First of all - stop use writeHead everywhere. Because it rewrite completely response headers.
首先 - 停止在任何地方使用 writeHead。因为它完全重写了响应头。
If tour write like this:
如果游记这样写:
res.writeHead(200,{"coolHeader":"YesIAm"});
res.writeHead(500);
then node.js will sent response just with status 500 and without header "coolHeader";
然后 node.js 将仅发送状态为 500 且没有标题“coolHeader”的响应;
If you wanna change Status Code, then use
如果您想更改状态代码,请使用
res.statusCode = ###;
If you wanna add new header use
如果你想添加新的标题使用
res.setHeader("key", "value");
And if you wanna rewrite all headers then use writeHeader(...)
如果你想重写所有标题然后使用 writeHeader(...)
Second. Add this code
第二。添加此代码
res.statusCode = 200;
//...
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
instead of your
而不是你的
res.writeHead(200, {
/// ...
'Access-Control-Allow-Origin' : '*'
});
and replace all writeHead(###)
with res.statusCode = ###;
并全部替换writeHead(###)
为res.statusCode = ###;
回答by Aweary
Try setting the `Access-Control-Allow-Origin' header on your response object in Node.
尝试在 Node.js 中的响应对象上设置“Access-Control-Allow-Origin”标头。
response.writeHead(200, {
/// ...
'Access-Control-Allow-Origin' : '*'
});
回答by jornare
Looks like you are calling .listen for both the app and the socket.io (I believe that is redundant since you are extending your server with socket.io)
看起来您正在为应用程序和 socket.io 调用 .listen (我认为这是多余的,因为您正在使用 socket.io 扩展您的服务器)
I have a little piece that works fine for me using socket.io 1.x I like to use https since it kills some issues with firewalls and antiviruses, but this example is rewritten to http.
我有一小部分可以很好地使用 socket.io 1.x 我喜欢使用 https,因为它可以解决防火墙和防病毒软件的一些问题,但是这个例子被重写为 http。
var http = require('http'),
socketio = require('socket.io'),
options={},
port=8080;
//start http
var app = http.createServer(options, handler),
io = socketio(app, {
log: false,
agent: false,
origins: '*:*'
// 'transports': ['websocket', 'htmlfile', 'xhr-polling', 'jsonp-polling']
});
app.listen(port);
console.log('listening on port ' + port);