1

This question tightly relates to This issue here.

I'm building an nodeJS app. You can see the file architecture in the screenshot below. enter image description here

When I try running my index.JS file:

const express = require('express')
const server     = new express()
const srcDir  = require('app-root-path');
const port = 3000

server.get('/', (req, res) => {
  res.sendFile(`${srcDir}/app/views/index.html`)
})


server.listen(port, () => {
  console.log(`App listening at http://localhost:${port}`)
})

Issue: I get a blank page, where the console says that everything supplementary in my "app" folder (APART FROM HTML FILES THEMSELVES!) (components (js files), assets (css), e.t.c.) is unreachable: Failed to load resource: the server responded with a status of 404 (Not Found). I know that the origin of the issue might be in establishing serve-static (which I don't understand), although it has always worked perfectly without it.

Can anyone help out? Thanks in advance.

P.S. Console logs: enter image description here

JoshJohnson
  • 181
  • 3
  • 18
  • Does this answer your question? [static files with express.js](https://stackoverflow.com/questions/10434001/static-files-with-express-js) – Michael Sep 02 '20 at 18:28

3 Answers3

1

You have to tell Express where the root directory of your static files is. Usually in the wild - this directory is called public and will contain all of your css, js files, which you want to ship to the browser. Do not include views or any other backend files.

So in your case: create a new directory called public and put assets and components in there.

Then in your Express server:

app.use(express.static(`${srcDir}/app/public`));
madflow
  • 7,718
  • 3
  • 39
  • 54
0

Try using the methods outlined in the express.js docs

const staticDir = './views' // Or wherever it's being served from
server.use(express.static(staticDir)); 

You can also choose a specified path pre-fix to show these files from

server.use('/static', express.static(staticDir))
DoubleJG
  • 85
  • 4
0

You need to add the "components" with express.static("directory"), like it's explained here: https://expressjs.com/en/starter/static-files.html

In your case, add this in your app.

server.use(express.static("app/components"));

To access the file FeaturePage/MainDisplay.js for example, you have to use this in your html.

<script src="/FeaturePage/MainDisplay.js"></script>
Paul
  • 99
  • 5