【发布时间】:2014-01-05 21:07:15
【问题描述】:
我正在创建一个用户可以登录的网络应用程序(密码/用户名)。登录后,他可以选择 2 个可用应用程序之一。 第一个应用程序在客户端和服务器之间使用 http 连接。 第二个使用网络套接字。所以当用户点击第二个应用程序时,应该建立一个 websocket。 我的第一个应用程序运行良好,第二个应用程序也运行良好,但是当我将所有应用程序放在一起时。我有问题。
这是我到目前为止所做的:
server.js
var app = express();
var server = http.createServer(app, function(req, res) {
//serves static files
//processes GET and POST requests of both the login page and the 1st app
}
server.listen(80, function() {
console.log("Server listening on port 80.");
});
app.configure(function () {
app.use(express.cookieParser());
app.use(express.session({secret: 'secret', key: 'express.sid'}));
});
app.get('/', function (req, res) {
var filePath = '../client/index.html';
if (filePath){
var absPath = './' + filePath;
serveStatic(res, cache, absPath); //function that serves static files
}
});
io = io.listen(server);
io.set('authorization', function (handshakeData, accept) {
//code
});
io.sockets.on('connection', function(socket) {
console.log('Client connected.');
});
index.html
<script src="../third-party/jquery-1.9.1.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
$(document).ready(function() {
tick = io.connect();
tick.on('data', function (data) {
console.log(data);
});
tick.on('error', function (reason){
console.error('Unable to connect Socket.IO', reason);
});
tick.on('connect', function (){
console.info('successfully established a working and authorized connection');
});
});
</script>
在客户端,我使用 jquery。
当我连接到我的本地主机时,我得到登录页面,并且在 chrome 调试器工具上显示一条错误消息:$ 未定义(在 index.html 中),GET http://localhost/third-party/jquery-1.9.1.min.js 404 (Not Found)
这是我的应用程序的架构:
- server
- server.js
-client
-index.html (login page)
-firstApp
-index.html
-secondApp (uses websocket)
-index.html
- third-party
-jquery-1.9.1.min.js
我相信,我没有以正确的方式提供静态文件。虽然,在将 websocket 添加到我的代码之前,我对此没有任何问题。 我不明白的是当我在
下记录一些东西时var server = http.createServer(app, function(req, res) {
console.log('TEST')
});
控制台上没有显示任何内容。 以下是提供静态文件的函数的方式:
function sendFile(res, filePath, fileContents) {
res.writeHead(200, {"content-type": mime.lookup(path.basename(filePath))});
res.end(fileContents);
}
function serveStatic(res, cache, absPath) {
//checks if file is cached in memory
if (cache[absPath]) {
sendFile(res, absPath, cache[absPath]); //serves file from memory
}else {
fs.exists(absPath, function(exists) { //checks if file exists
if (exists) {
fs.readFile(absPath, function(err, data) { //reads file from disk
if (err) {
}else {
cache[absPath] = data;
sendFile(res, absPath, data); //serves file from disk
}
});
}else {
console.log('cannot find the file')
send404(res);
}
});
}
}
【问题讨论】:
标签: jquery node.js express socket.io