expressjsHow do I serve an index.html file using Express.js?
To serve an index.html
file using Express.js, you will need to create a route that will serve the index.html
file. The following code block will create a route that will serve the index.html
file located in the public
directory:
const express = require('express');
const app = express();
app.use(express.static(__dirname + '/public'));
app.get('/', (req, res) => {
res.sendFile(__dirname + '/public/index.html');
});
app.listen(3000, () => {
console.log('Server started on port 3000');
});
The code above will create a route that will serve the index.html
file located in the public
directory when the route is accessed.
Code explanation
const express = require('express');
: This line imports the Express.js library.const app = express();
: This line creates an Express.js application.app.use(express.static(__dirname + '/public'));
: This line tells Express.js to serve static files from thepublic
directory.app.get('/', (req, res) => {
: This line creates a route that will be called when the root route is accessed.res.sendFile(__dirname + '/public/index.html');
: This line tells Express.js to serve theindex.html
file located in thepublic
directory.app.listen(3000, () => {
: This line tells Express.js to listen for requests on port 3000.
Helpful links
More of Expressjs
- How can I use express-zip js to zip and download files?
- How do I use Zod with Express.js?
- How do I find Express.js tutorials on YouTube?
- How do I use Express.js to handle x-www-form-urlencoded data?
- How can I use Express.js and Vite together for software development?
- How do I manage user roles in Express.js?
- How can I maximize the number of connections in Express.js?
- How do I use the expressjs urlencoded middleware?
- How do I use Express.js to parse YAML files?
- How do I use Express.js with W3Schools?
See more codes...