我知道在 SO 上对此主题进行了一些讨论,但我找不到我的问题的答案。我在 localhost:8020 上使用 Aptana 在服务器上运行了一个网页。页面上的 javascript 正在访问我在 localhost:1337 上运行的节点服务器。这是节点代码:
var io = require('socket.io');
var http = require('http');
var sys = require('sys');
var json = [];
var server = http.createServer(function (req, res) {
var headers = {};
headers["Access-Control-Allow-Origin"] = "*";
headers["Access-Control-Allow-Methods"] = "POST, GET, PUT, DELETE, OPTIONS";
headers["Access-Control-Allow-Credentials"] = true;
headers["Access-Control-Max-Age"] = '86400'; // 24 hours
headers["Access-Control-Allow-Headers"] = "X-Requested-With, Access-Control-Allow-Origin, X-HTTP-Method-Override, Content-Type, Authorization, Accept";
res.writeHead(200, headers);
res.end();
});
server.listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
var socket = io.listen(server);
socket.on('connection', function(){
console.log("Connected");
});
我通过更改标头来处理 cors 请求,我一直这样做。我的客户端代码通常是 socket.io 初学者的东西。这是我的代码中的标签:
<script src="http://cdn.socket.io/stable/socket.io.js"></script>
<script>
// Create SocketIO instance
var socket = new io.Socket('localhost',{
port: 1337
});
socket.connect();
// Add a connect listener
socket.on('connect',function() {
log('<span style="color:green;">Client has connected to the server!</span>');
});
// Add a connect listener
socket.on('message',function(data) {
log('Received a message from the server: ' + data);
});
// Add a disconnect listener
socket.on('disconnect',function() {
log('<span style="color:red;">The client has disconnected!</span>');
});
// Sends a message to the server via sockets
function sendMessageToServer(message) {
socket.send(message);
log('<span style="color:#888">Sending "' + message + '" to the server!</span>');
}
// Outputs to console and list
function log(message) {
var li = document.createElement('li');
li.innerHTML = message;
document.getElementById('message-list').appendChild(li);
}
当我运行代码时,我不断收到“XMLHTTPRequest ... Origin is not allowed by Access-Control-Allow-Origin”错误。我的浏览器是chrome。1. 为什么我的浏览器使用的是 XMLHTTPRequest 而不是 Websocket?2. 为什么我在更改标题时收到访问控制错误?感谢您提前提供的所有帮助。