Reputation: 39
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.
Upvotes: 2
Views: 4026
Reputation: 101
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)
Upvotes: 4