I'm attempting to build a server for my current project but I'm new to Express. My file directory looks like this:
root-directory
├── public
│ ├── css
│ │ └── styles.css
│ ├── images
│ │ └── img1.png
| | └── img2.png
| | └── img3.png
│ └── index.html
| └── main.js
└── server
└── app.js
This is the code I am using in my server:
const express = require('express');
const path = require('path');
const app = express();
app.use('/static', express.static('public'));
app.use(express.json());
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, '../public/index.html'))
});
const port = 5000;
app.listen(port, () => console.log(`Server is listening on port ${port}.`))
Currently, the server is only displaying my static HTML file, and none of the JavaScript or CSS that is linked to it. I have attempted altering my sendFile function to look like this: res.sendFile(path.join(__dirname, '../public')); but that results in an Error: Cannot GET /.
How can I reconfigure my server to display my HTML, CSS, and JavaScript all at once?
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, '../public/index.html'))
});
You don't need to respond to all GET requests (because of the use of '*') with the index.html file. Moreover, it conflict with the line app.use('/static', express.static('public'));.
/static in this line with /app.use('/static', express.static('public'));
Then your app will find index.html in the public folder to respond to the GET '/' request.
index.html file if the link to CSS/JS/image files is valid. For example, the link to style.css file should be: <link rel="stylesheet" href="/css/style.css">.