我正在尝试使用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.
以下是我使用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);
});
}
有谁知道如何解决我的问题?
亲切的看法/ H
答案 0 :(得分:6)
首先 - 停止在任何地方使用writeHead。因为它会重写完整的响应头。
如果游览写得像这样:
res.writeHead(200,{"coolHeader":"YesIAm"});
res.writeHead(500);
然后node.js将发送状态为500且没有标题“coolHeader”的响应;
如果您想更改状态代码,请使用
res.statusCode = ###;
如果您想添加新标题,请使用
res.setHeader("key", "value");
如果您想重写所有标题,请使用writeHeader(...)
二。添加此代码
res.statusCode = 200;
//...
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
代替你的
res.writeHead(200, {
/// ...
'Access-Control-Allow-Origin' : '*'
});
并将所有writeHead(###)
替换为res.statusCode = ###;
答案 1 :(得分:4)
尝试在Node中的响应对象上设置`Access-Control-Allow-Origin'标头。
response.writeHead(200, {
/// ...
'Access-Control-Allow-Origin' : '*'
});
答案 2 :(得分:3)
看起来你正在为应用程序和socket.io调用.listen(我认为这是多余的,因为你使用socket.io扩展你的服务器)
我有一个小块,对我来说使用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);