Warm tip: This article is reproduced from serverfault.com, please click

Node.js cannot find client-side files

发布于 2020-11-30 03:15:49

I have a simple node.js app:

server.js

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

const PORT = 8080;

app.use(express.static('client'));

// Start the express web server listening on 8080
app.listen(8080, () => {
  console.log('Service started on port 8080.');
});

// Serve the homepage
app.get('/', (req, res) => {
  res.sendFile(__dirname + '/index.html');
});

index.html

<html>
... irrelevant junk ...
<script src="js/client.js"></script>
</html>

However, when I run node server.js and open localhost:8080, the console complains that it can't find http://localhost:8080/javascript/client.js.

Obviously, I want it to be looking at ./javascript/client.js, instead of rooted at the locahost addr -- how to resolve?

The folder hierarchy is simple:

.
├── index.html
├── server.js
├── js
    └── client.js

I've tried to change public to client as suggested here but that didn't help.

Questioner
Alex Coleman
Viewed
0
jfriend00 2020-11-30 11:35:19

Based on where your files are located on the server, you should make three changes:

app.use(express.static("./public"));

And, in the client, use this:

<script src="/js/client.js"></script>

Then, move your client-side files below the server-side files into a root public directory like this:

.
├── index.html
├── server.js
├── public
    ├── js
        └── client.js

Without moving the client-side files into public, then you open up your server-side code to being read by the client (which you do not want).


Here's how this works:

The client requests:

http://localhost:8080/js/client.js

express.static() sees a request for:

 /js/client.js

It starts at the root of your public files and combines /js/client.js onto the public directory path which then creates the right path to access:

public/js/client.js

You could have made it work without moving the client-side files into the public directory hierarchy, by just doing this:

app.use(express.static(__dirname));

But, then that would have opened up all your server-side files to be read by the client which you really do not want.