can not find static files on multilevel routes in express js
To serve static files in Express.js on multilevel routes, you can follow these steps:
Install the required dependencies:
npm install express
Require the Express.js module and create an instance of the Express application:
javascript const express = require('express'); const app = express();
Set up the middleware to serve static files using the
express.static
function. This function takes the root directory of the static files as an argument:javascript app.use(express.static('public'));
Create the necessary routes for your application. In this case, we'll create a multilevel route:
javascript app.get('/multilevel/route', (req, res) => { res.sendFile(__dirname + '/public/index.html'); });
The app.get
function is used to define a route for the GET method. In this example, the route is /multilevel/route
. When a GET request is made to this route, the callback function is executed.
Inside the callback function, the res.sendFile
function is used to send the index.html
file located in the public
directory. The __dirname
variable represents the current directory.
- Start the server by listening on a specific port:
javascript const port = 3000; app.listen(port, () => { console.log(`Server is running on port ${port}`); });
In this example, the server is listening on port 3000. You can choose a different port if needed.
- Create the necessary directory structure: ```
- project
- public
- index.html ```
In this example, the index.html
file is placed inside the public
directory.
- Run the application by executing the JavaScript file:
node app.js
Replace app.js
with the name of your JavaScript file.
Now, when you access http://localhost:3000/multilevel/route
, the server will serve the index.html
file located in the public
directory.