跨node.js服务器跨域错误

我是一个node.js的新手,我想设置我的第一个安装。 我有一个server.js我定义一个新的服务器:

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: 'flipper', database: 'oclock', //database: 'nodejs', port: 3306 }), POLLING_INTERVAL = 3000, pollingTimer; // If there is an error connecting to the database connection.connect(function(err) { // connected! (unless `err` is set) if (err) { 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) { 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); }); } 

接下来,我创build一个client.html文件,该文件应该连接到服务器并检索数据:

 <div id="container">Loading ...</div> <script src="node_modules/socket.io/node_modules/socket.io-client/socket.io.js"></script> <script src="http://code.jquery.com/jquery-latest.min.js"></script> <script> // create a new websocket var socket = io.connect('http://oclock.dyndns.org:8000'); // on message received we print all the data inside the #container div socket.on('notification', function (data) { var usersList = "<dl>"; $.each(data.users,function(index,user){ usersList += "<dt>" + user.user_name + "</dt>\n" + "<dd>" + user.user_description + "\n" + "<figure> <img class='img-polaroid' width='50px' src='" + user.user_img + "' /></figure>" "</dd>"; }); usersList += "</dl>"; $('#container').html(usersList); $('time').html('Last Update:' + data.time); }); </script> 

当我尝试使用url http://oclock.dyndns.org/client.html使用client.html连接到服务器时,我发现该请求被阻止以获取跨源请求。 请求url是http://oclock.dyndns.org:8000/socket.io/?EIO=3&transport=polling&t=1428917662987-0 。

我错过了什么? 我究竟做错了什么?

起源是基于:

  • 计划(在这两种情况下http)
  • 主机名(两种情况下都是oclock.dyndns.org)
  • 端口号(一个是80,另一个是8000)

所以你有不同的起源。 照常设置CORS 。