【发布时间】:2015-01-30 21:29:49
【问题描述】:
我正在尝试使用 socket.io 学习 nodejs,目前我正在使用this tutorial by 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.
这是我的套接字代码的一部分。
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);
});
}
有人知道我该如何解决我的问题吗?
亲切的问候/H
【问题讨论】:
-
您需要设置
Access-Control-Allow-Origin标头。您使用的是纯 Node.JS 还是 Express? -
我没有使用 Express,因为您现在可以在已编辑的问题中看到。我应该在哪里放置 Access-Control-Allow-Origin?
-
你的client.html是什么样的?
-
你用的是什么版本的socket.io?
标签: javascript node.js socket.io