server.js
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
socket.on('chat message', function(msg){
io.emit('chat message', msg);
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
的index.html
<!doctype html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Socket.IO chat</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="chat">
<ul id="messages"></ul>
<input id="m" autocomplete="off">
<div id="button">Send</div>
</div>
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script>
var socket = io();
$('#button').on('click touchstart', function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
socket.on('chat message', function(msg){
$('#messages').append($('<li>').text(msg));
});
</script>
</body>
</html>
我在运行Windows 8.0 x64的桌面PC上启动我的服务器,然后我在路由器上转发端口,然后我连接到例如我的手机转到xxx.xxx.xxx.xxx:3000(当前家庭IP地址)一切正常好的,直到我想从我的&#34;服务器&#34;中包含外部jquery。和css文件style.css也来自服务器。我在堆栈上读到有一些叫做静态路径的方法所以我在我的项目文件夹中创建了#34; public&#34;我用过:
app.use(express.static(path.join(__dirname, 'public')));
我在这里找到:Node.js - external JS and CSS files (just using node.js not express)
但是堆栈上显示的单个方法不起作用,它会不断返回几个错误:
is not an object
is not defined
或只是服务器启动但找不到文件
我的高清路径是:
C:\Users\Patryk\Desktop\nodeproject\index.html
C:\Users\Patryk\Desktop\nodeproject\server.js
C:\Users\Patryk\Desktop\nodeproject\node_modules\...
C:\Users\Patryk\Desktop\nodeproject\public\...
答案 0 :(得分:2)
听起来你可能没有正确的顺序。您需要在路由之前声明静态路径。像这样:
var express = require('express');
var app = express();
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
以下是server.js
文件的更新版本:
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
socket.on('chat message', function(msg){
io.emit('chat message', msg);
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});