这是 html 页面。我从 node.js 服务器调用此页面,即 app.js。这里我无法加载 socket.io.js、bootstrap.js、bootstrap.css 页面。
我的 index.html:
<html>
<script type="text/javascript" src="/javascripts/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script type ="text/javascript" src="/javascripts/bootstrap.js"></script>
<link rel="stylesheet" type="text/css" href="/stylesheets/bootstrap.css" />
<div id="progressbar">
</div>
<script>
var socket = io('http://localhost:8085');
socket.on('connect', function(){});
socket.on('message', function(data){
$('#progressbar').progressbar({
maximum: 100,
step: JSON.parse(data).percent
});
});
socket.on('disconnect', function(){});
</script>
</html>
我的 app.js 代码:
var app = express ();
var http = require('http').Server(app);
var io = require('socket.io')(http);
http.listen(8085, function(){
console.log('listening on *:8085');
});
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
//res.send('Hello World!');
});
最佳答案
您为静态文件设置了错误的路径。
在你的情况下,你需要使用这个:
app.use('/javascripts', express.static(__dirname + '/javascripts'));
app.use('/stylesheets', express.static(__dirname + '/stylesheets'));
现在,javascripts 和 stylesheets 文件夹中的任何文件都将作为静态文件加载。
您当前使用静态文件的方法:
app.use(express.static(path.join(__dirname, 'public')));
这会将 public 文件夹下的所有内容作为静态文件加载,因此如果您需要将 javascripts 和 stylesheets 文件夹移到那里希望它起作用。
关于javascript - 无法在 node.js 中加载 js 和 css 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33753718/