【发布时间】:2023-03-03 02:35:01
【问题描述】:
我是 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);
});
}
接下来我创建一个 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>
当我尝试使用 client.html 使用 url http://oclock.dyndns.org/client.html 连接到服务器时,我看到该请求因跨源请求而被阻止。请求地址为http://oclock.dyndns.org:8000/socket.io/?EIO=3&transport=polling&t=1428917662987-0。
我错过了什么?我做错了什么?
【问题讨论】:
标签: javascript node.js