繁体   English   中英

在Node.js中加载客户端Javascript和CSS

[英]Load client Javascript and CSS in Node.js

我想在我的html文件中加载客户端javascript chat.js和css style.css ,但是在加载它们时出现404错误。

这是我的服务器文件:

// routing
app.get('/', function (req, res) {
  res.sendFile(__dirname + '/index.html');
});

这是我的客户html:

<script src="/socket.io/socket.io.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="chat.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">

如何将它们加载到我的应用程序中? 所有文件都在同一根文件夹中。 我试过了,但是没有用:

app.get('/', function (req, res) {
  res.sendFile(__dirname + '/chat.js');
});

看起来您正在使用Express Web框架,因此在这种情况下,应根据需要使用Express静态中间件

我做了一个下面的例子。

这是服务器server.js文件:

var express = require('express');
var app = express();

app.use(express.static(__dirname + '/public'));

app.listen(4040, function() {
  console.log('server up and running');
});

您在其中看到Express正在提供驻留在public目录中的文件的位置。 您看到我没有为/提供路由,因为浏览器会自动获取index.html


public/index.html

<!doctype html>
<html>
  <head>
    <link href="style.css" rel="stylesheet"/>
  </head>
  <body>
    <h1>Hey</h1>
    <script src="app.js"></script>
  </body>
</html>

从浏览器的角度来看,他只知道index.htmlapp.jsstyle.css文件,因为它们是由express提供的。


public/style.css

body {                                                          
    background: red;                                            
}

public/app.js

document.addEventListener('DOMContentLoaded', function() {
  alert('hello world');
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM