Tôi đang cố gắng tìm hiểu nodej với socket.io và tại thời điểm này tôi đang sử dụng this tutorial by GianlucaGuarini. Khi nhập tệp client.html của tôi, tôi nhận được lỗi sau. Tôi biết nó có nghĩa là gì và nó ở đó để ngăn chặn các kịch bản trình duyệt Cross nhưng tôi không biết cách cho phép tập lệnh nodejs của tôi truy cập vào tệp client.html.Socket.io Không có tiêu đề 'Access-Control-Allow-Origin' xuất hiện trên tài nguyên được yêu cầu. Do đó, gốc 'http: // localhost' không được phép truy cập
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.
Đây là một phần của mã của tôi có ổ cắm.
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);
});
}
Có ai biết cách giải quyết vấn đề của tôi không?
Quan tâm/H
Bạn cần đặt tiêu đề 'Access-Control-Allow-Origin'. Bạn đang sử dụng Node.JS thuần túy hay có thể là Express? – Aweary
Tôi không sử dụng Express như bạn có thể truy cập ngay trong câu hỏi đã chỉnh sửa. Tôi sẽ đặt Access-Control-Allow-Origin ở đâu? – hgerdin
Client.html của bạn trông như thế nào? –