简体   繁体   中英

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.

This is my server file:

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

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

I did an example that is below.

here is the server server.js file:

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. You see I didn't provide a route for / since the browser automatically is going to grab the 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.


public/style.css :

body {                                                          
    background: red;                                            
}

public/app.js

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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