我创建了一个简单的 Node JS
程序。我在 app.js
所在的同一文件夹中有 index.html
和外部 css
和 js
文件public/stylesheets/style.css
和 /public/javascripts/script.js
目录。当我直接从浏览器打开 index.html
时,css
文件会自动链接到 html
文件。但是当我运行 node app.js
并导航到 http://localhost:3000
时,显示了 index.html
但没有显示任何样式对它没有影响。我该如何解决?
app.js
文件是这个
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
server.listen(3000);
app.get('/', function(req, res){
res.sendfile(__dirname + '/index.html');
});
index.html
文件是这个
<html>
<head>
<title>Sanitizor</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script src="public/javascripts/script.js"></script>
<link rel="stylesheet" type="text/css" href="public/stylesheets/style.css">
</head>
<body>
<h3>hello</h3>
<div id="chat"></div>
<form id="sent-message">
<input size="35" id="message"></input>
<input type="submit"></input>
</form>
</body>
</html>
最佳答案
您需要启用静态服务:
app.use(express.static(path.join(__dirname, 'public'))); //this line enables the static serving in the public directory
您的 public
目录可能如下:
public
|_css
|_js
|_images
|_logo.png
然后,如果你想得到一张图片:
http://localhost:3000/images/logo.png
如果你想在你的 html 页面中显示它:
<img id="logo" src="/images/logo.png"/>
在您的情况下,替换以下行
<script src="public/javascripts/script.js"></script>
由
<script src="/javascripts/script.js"></script>
CSS 也是如此
关于javascript - 当 Node.js 调用 HTML 时,外部 Javascript 和 CSS 不会影响 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36674425/