服务器.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 的台式电脑上启动服务器,并在路由器上转发端口,然后我从手机连接到 xxx.xxx.xxx.xxx:3000(当前家庭 IP 地址),一切正常好吧,直到我想包含来 self 的“服务器”的外部 jquery 和来自服务器的 css 文件 style.css 。我在堆栈上读到有一种称为静态路径的方法,因此我在项目文件夹“public”中创建了它并使用了:
app.use(express.static(path.join(__dirname, 'public')));
我在这里找到的:Node.js - external JS and CSS files (just using node.js not express)
但堆栈上提供的单个方法不起作用,它不断返回几个错误:
不是对象
未定义
或者只是服务器启动但找不到文件
我的高清路径是:
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\...
最佳答案
听起来你的东西可能没有按正确的顺序排列。您需要在路由之前声明静态路径。像这样的事情:
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');
});
关于javascript - 如何在从外部连接时将外部文件包含到 Node js 项目中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29189098/