javascript - 当 Node.js 调用 HTML 时,外部 Javascript 和 CSS 不会影响 HTML

标签 javascript html css node.js

我创建了一个简单的 Node JS 程序。我在 app.js 所在的同一文件夹中有 index.html 和外部 cssjs 文件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/

相关文章:

javascript - Firefox 3 扩展 JavaScript 加载时重复事件监听器

javascript - 如何访问表兄弟元素,在 Cypress 中具有标识符的元素

html - SVG 不在 linkedin 中显示图像

javascript - 如何减少对每个空选择使用错误消息

html - 如何设置通知警报的高度和宽度

css - 我应该如何覆盖 anchor 标记中 div 的悬停样式?

javascript - Array.filter 没有返回预期的输出

javascript - 如何在 JavaScript 中添加/删除类?

css - CSS文件中有顺序吗?为什么要加下划线 (a href)

javascript - HTML平滑滚动[没有 anchor 动画]?