简体   繁体   English

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

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

I want to load client side javascript chat.js and css style.css in my html file but i get a 404 error while loading them. 我想在我的html文件中加载客户端javascript chat.js和css style.css ,但是在加载它们时出现404错误。

This is my server file: 这是我的服务器文件:

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

This is my client 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">

How can I load them in my app? 如何将它们加载到我的应用程序中? All files are in the same root folder. 所有文件都在同一根文件夹中。 I tried this but it doesn't work: 我试过了,但是没有用:

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

Looks like you are using express web framework so in that case you should use the express static middleware for your purposes. 看起来您正在使用Express Web框架,因此在这种情况下,应根据需要使用Express静态中间件

I did an example that is below. 我做了一个下面的例子。

here is the server server.js file: 这是服务器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');
});

Where you see that Express is serving the files that resides on public directory. 您在其中看到Express正在提供驻留在public目录中的文件的位置。 You see I didn't provide a route for / since the browser automatically is going to grab the index.html . 您看到我没有为/提供路由,因为浏览器会自动获取index.html


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>

From the perspective of the browser he only knows the index.html , app.js , and style.css files since they were provided by express. 从浏览器的角度来看,他只知道index.htmlapp.jsstyle.css文件,因为它们是由express提供的。


public/style.css : 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