简体   繁体   中英

Node.js serve HTML, but can't load script files in served page

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? Ps 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>

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'));
});

创建一个虚拟路径。

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

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