Home > Software engineering >  Express.js not serving local javascript
Express.js not serving local javascript

Time:10-15

I am learning express.js and trying to run local JavaScript file on node server. But express is not able to serve the static files.

File structure:

Express
-public
--JS
---client.js
--index.html

-index.js

index.js

const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);

console.log(path.join(__dirname,'/public'));
app.use(express.static(path.join(__dirname,'/public')));

app.get('/', (req, res) => {
    res.sendFile(__dirname  '/public/index.html');
});

server.listen(3000, () => {
  console.log('listening on *:3000');
});

index.html

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script defer src="../public/JS/client.js"></script>
</head>
<body>
     
    done..

</body>
</html>

server's console log show for path

E:\node js\express\public

errors in the browser console

localhost/:7 GET http://localhost:3000/public/JS/client.js net::ERR_ABORTED 404 (Not Found)

localhost/:1 Refused to execute script from 'http://localhost:3000/public/JS/client.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.

CodePudding user response:

The src attribute needs to contain the URL to the JavaScript.

The browser doesn't know there the HTML document or the JS file are stored on your servers file system.

app.get('/' means your HTML document is at /. You can't go up any higher than that so ../ is meaningless.

app.use(express.static(path.join(__dirname,'/public'))); means that any request for a URL will cause the server to look inside the public directory for a match. So if you ask for /foo it will look for foo inside the public directory.

You are asking for public/JS/client.js so it is looking for public inside the public directory.

The real URL to your JS is: /JS/client.js.

CodePudding user response:

The path to the client.js file in the HTML is incorrect. The path for all assets in the HTML file should be relative to the HTML file.

In your case, index.html is in public folder and the client.js is inside public/JS folder.

So, the script tag should be like this. Hope this helps!

<script defer src="JS/client.js"></script>
  • Related