Node.js serve HTML, but can't load script file

2020-07-10 09:52发布

问题:

i'm trying to make a little login page using a mongoDB database and Node.js + express. I'm new to Node.js so maybe the solution is easier than i thought. The problem is: when i serve the HTML file when connecting to the server page, i can't use the JavaScript file referenced in the html file. How can i fix it? P.s the index.html and client.js files are all located in a folder named "client".

Code:

var express = require('express');
var path = require('path');
var app = express();
app.use(express.static(__dirname + 'client'));
app.get('/', function(req, res) {
    res.sendFile(path.join(__dirname + '/client/index.html'));
});

HTML File:

 <!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Login</title>
    <meta name="description" content="Login Page">
    <meta name="author" content="AlbertoCoder">
    <script src="/client/client.js"></script>
</head>
<body>
</body>
</html>

回答1:

You're able to use it, but you need to serve that javascript file from your server through a valid path.

In your HTML you're trying to retrieve the javascript file from /client/client.js

The hint here is:

Imagine the following URL of your server http://myserver:8080/

Now, your HTML is trying to retrieve the js file through http://myserver:8080/client/client.js

As you can see, your server is not serving that assets, thus you won't be able to retrieve that js file.

Do the following:

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

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


回答2:

Create a virtual path.

app.use('/client', express.static(path.join(__dirname, 'client')));