0
votes

My folder structure is :

APP
 -public
   main.js
 -views
   index.html
 index.js

I am trying to serve the static file to express server but its not working. The code for this in my index.js file is:

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

app.use(express.static(__dirname+'/public'));

I have also tried using path.join syntax

In my index.html file in the views folder , I am using the src tag as 'main.js'

<script type="text/javascript" src="main.js"></script>

I get the error net::ERR_FILE_NOT_FOUND. I can also see that path src is referring to is wrong. It is looking for main.js file in views directory instead of looking in public directory.

I have looked at other answers. I understand the syntax theoretically but am not able to find what I am doing wrong

Please point out the issue in my code. Thanks

1
Have you tried app.use(express.static(__dirname+'../public')); - ArchNoob
just tried it.. getting the same error - Parvarish
Lol.. sure am sorry I thought the index.js file was inside another directory. I just checked docs they suggest this approach now app.use(express.static('public')) - ArchNoob
no issues :)..well i tried that too , doesnt work...infact its better to use the absolute path so that the path is valid even if we access the static files from somewhere other than the project directory..I have done this many times before..dont know what seems to be the issue this time.. - Parvarish
Hi..I was able to fix this issue...I had just added the index.html in my project directory without serving the file in any of the routes..So in my routes I added the code to render my index.html file simply like res.sendFile('index.html)..and it worked. - Parvarish

1 Answers

0
votes

Here is a working example:

index.js:

const express = require('express');
const path = require('path');
const app = express();
const port = 3000;

app.use(express.static(__dirname + '/public'));
app.get('/', (req, res) => {
  res.sendFile(path.resolve(__dirname, './views/index.html'));
});

app.listen(port, () => console.log(`server is listening on port ${port}`));

./public/main.js:

window.onload = function() {
  console.log('onload');
};

./views/index.html:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script type="text/javascript" src="main.js"></script>
  </head>
  <body>
    This is template
  </body>
</html>