我正在尝试通过 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
最佳答案
首先 - 停止在任何地方使用 writeHead。因为它完全重写了响应头。
如果tour这样写:
res.writeHead(200,{"coolHeader":"YesIAm"});
res.writeHead(500);
然后 node.js 将发送状态为 500 且没有 header “coolHeader”的响应;
如果你想改变状态码,那么使用
res.statusCode = ###;
如果你想添加新的标题使用
res.setHeader("key", "value");
如果您想重写所有 header ,请使用 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 = ###;
关于javascript - Socket.io 请求的资源上不存在 'Access-Control-Allow-Origin' header 。因此不允许访问 Origin 'http://localhost',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28244932/