我想在我的PHP Web應用程序中使用nodeJS。我遵循nodejs教程,並且在localhost:3000
上運行時工作正常,但我想在url
上運行,就像這個localhost/final/chat/chat_index.html
文件一樣。所以我所做的是下面的代碼可以在nodeJS中調用Socket.on():解決方案
chat_index.html
<div id="newUser">
<form id="user">
<input id="username">
<input type="submit">
</form>
</div>
$(document).ready(function(){
var socket = io.connect('http://localhost:3000/final/chat/chat_index.html',
{resource:'https://cdn.socket.io/socket.io-1.2.0.js'});
$('#user').submit(function(){
socket.emit('new user', $('#username').val());
});
}); // document.ready ends here
</script>
index.js這是服務器端的JS文件
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/final/chat/chat_index.html', function(req, res){
res.sendFile(__dirname + '/chat_index.html');
});
io.of('/final/chat/chat_index.html').on('connection', function(socket){
console.log('connected user');
socket.on('new user', function(user){
console.log(user);
});
});
http.listen(3000, function(){
console.log('listening to port');
});
以上chat_index.html
頁面加載,顯示在窗體它。當我通過這個表單服務器端提交一些數據時,js沒有獲取數據。
在我的代碼中缺少某些東西,或者我在代碼中做錯了什麼。 在此先感謝
問題解決了'io.of('/ final/chat/chat_index.html')'應該在'io'方法之前使用 –