expressjsHow can I render HTML pages using Express.js?
Express.js is a web application framework for Node.js that enables you to render HTML pages. To render HTML pages using Express.js, you need to create a route for the HTML page and use the res.sendFile
method. Here is an example of how to do this:
//Import Express.js
const express = require('express');
//Create an instance of Express.js
const app = express();
//Create a route for the HTML page
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
//Start the server
app.listen(3000, () => {
console.log('Server started on port 3000');
});
Output example
Server started on port 3000
- Import Express.js - This imports the Express.js module.
- Create an instance of Express.js - This creates an instance of Express.js.
- Create a route for the HTML page - This creates a route that will render the HTML page when the route is accessed.
- Use the
res.sendFile
method - This method is used to send the HTML page to the browser. - Start the server - This starts the server so that the HTML page can be rendered.
Helpful links
More of Expressjs
- How do I set the time zone in Express.js?
- How do I find Express.js tutorials on YouTube?
- How can I use Express.js and Vite together for software development?
- How can I use Express.js with TypeScript?
- How can I use the x-forwarded-for header in Express.js?
- How do I set up a YAML configuration file for a Node.js Express application?
- How do I manage user roles in Express.js?
- How do I use Zod with Express.js?
- How can I use Node.js and Express together to create a web application?
- How do I use Express.js and Yarn together in a software development project?
See more codes...