2

I have a directory structure like this :

    server
       code
         app.js
         web
           html
               index.html
           css
               index.css
           scripts
               index.js

My app.js code is trying to serve the html file index.html but shows errors this is the code :

    app.get('/web',function(req,res) 
    {
        res.sendFile('../web/html/index.html');
    })

What path to pass to sendFile() and make it work appropriately so that the script file and css are also found by the html file when it runs ?

I'm new to node.js.

halfer
  • 19,824
  • 17
  • 99
  • 186
harshm31
  • 39
  • 1
  • 4

1 Answers1

4

You can use express.static("") to serve static files. Example:

const express = require("express");
const app = express();
const server = app.listen(PORT, () => {});
app.use(express.static("./web"));

This will make everything in the web folder public, and the index.html file can be found at localhost:PORT/html/index.html This will also serve your js and css files correctly

To serve the html separately you will need to use an absolute path:

app.get('/web',function(req,res) 
{
    res.sendFile(path.join(__dirname, './web/html/index.html'));
})

remember to include const path = require(path)

01101010
  • 81
  • 1
  • 7
  • 1
    quick comment -- based on the directory structure above, it looks like `web/` is in the same folder as `app.js`. unless OP would like to clarify that part via screenshot. – Jhecht Dec 28 '18 at 23:23