Languages
[Edit]
EN

Express.js - send HTML file in response

0 points
Created by:
Mikolaj
519

In this article, we would like to show you how toΒ send HTML file in responseΒ in express.js.

1. Import path module

To deal with file paths you need to import the node.js path module using the following command:

const path = require('path');

2. Use res.sendFile() method

In below example we:

  • Use theΒ res.sendFile() method within the request. The method takes the path argument.
  • Use path.join() to specify the path argument:
    • __dirname - current directory

    • 'index.html' - the HTML file we want to send

Now our path inside res.sendFile() method looks like this: C:\project\index.html

When the project folder looks like this

/C/
 └── project/
      β”‚
      β”œβ”€β”€ index.js
      β”œβ”€β”€ index.html
      β”œβ”€β”€ package.json
      └── package-lock.json

Pracrical example:

const express = require('express');
const path = require('path');

const app = express();

// set HTML file as a response 
app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, 'index.html'));
});

app.listen(5000);

Result:

Node.js / Exoress.js - HTML file as a response
Node.js / Exoress.js - HTML file as a response

Alternative titles

  1. Express.js - send index.html file in response
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
πŸš€
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

β€οΈπŸ’» πŸ™‚

Join