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 do I implement CSRF protection in an Express.js application?
- How do I set the time zone in Express.js?
- How do I find Express.js tutorials on YouTube?
- How do I manage user roles in Express.js?
- How do I render a template using Express.js?
- How can I disable the X-Powered-By header in Express.js?
- How can I parse XML data using Express.js?
- What is Express.js and how is it used for software development?
- How can I use Express.js with TypeScript?
- How can I set up unit testing for an Express.js application?
See more codes...