Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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? 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>
like image 449
Alberto Calabrese Avatar asked Jan 01 '18 14:01

Alberto Calabrese


1 Answers

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'));
});
like image 169
Ele Avatar answered Oct 22 '22 19:10

Ele