我目前正在为手机应用程序聊天,但遇到了一些跨域问题。下面是我的代码(由我在网上找到的不同来源组合而成):
server.js(随节点提供):
var express = require('express')
, app = express()
, server = require('http').createServer(app)
, io = require('socket.io').listen(server)
, conf = require('./config.json');
// Enables CORS
var enableCORS = function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
// intercept OPTIONS method
if ('OPTIONS' == req.method) {
res.send(200);
}
else {
next();
}
};
// enable CORS!
app.use(enableCORS);
// Webserver to port
server.listen(conf.port);
app.configure(function(){
app.use(express.static(__dirname + '/public'));
});
// on path /
app.get('/', function (req, res) {
// so wird die Datei index.html ausgegeben
res.sendfile(__dirname + '/public/index.html');
});
// Websocket
io.sockets.on('connection', function (socket) {
socket.emit('chat', { zeit: new Date(), text: 'You are now connected to the server.' });
socket.on('chat', function (data) {
// send to all
io.sockets.emit('chat', { zeit: new Date(), name: data.name || 'Anonym', text: data.text });
console.log(data.name + ': ' + data.text);
});
});
// display port in console
console.log('Server running on port ' + conf.port);
服务器只是用于测试的临时代码
客户:
$('#chat' ).live( 'pageshow',function(){
function makeid()
{
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for( var i=0; i < 5; i++ )
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
// WebSocket
var chatServer = '192.168.61.201:8082';
var clientID = localStorage.getItem('login.user');
var socket = io.connect(chatServer);
socket.on('connect', function () {
socket.emit('hi!');
});
// new message
socket.on('chat', function (data) {
var zeit = new Date(data.zeit);
var append;
if(data.name == clientID)
{
append = $('<p class="speech-me"></p>').append(data.text);
}
else
{
append = $('<p class="speech-them"></p>').append(data.text);
}
$('#content').append(append);
// scroll down
$('body').scrollTop($('body')[0].scrollHeight);
});
// send message
function senden(){
var name = clientID;
var text = $('#text').val();
socket.emit('chat', { name: name, text: text });
$('#text').val('');
}
$('#senden').click(senden);
$('#text').keypress(function (e) {
if (e.which == 13) {
senden();
}
});
});
在服务这个槽apache时一切正常,但在文件:// base我得到以下错误:
GET http://file/socket.io/?EIO=2&transport=polling&t=1405669552105-1
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://file/socket.io/?EIO=2&transport=polling&t=1405669552105-1. This can be fixed by moving the resource to the same domain or enabling CORS.
我希望这里的某人可能比我的谷歌搜索工作更好。
非常感谢。