Serving HTML with Express Documentation

1. Introduction

This page demonstrates how to serve HTML content using Express, and how to fetch data from an Express endpoint in a client-side application.

2. Example of Serving HTML

Express provides the res.sendFile method to serve static files, including HTML. Below is an example of serving an HTML file named index.html:

const express = require('express');

const app = express();
const PORT = 8080;

app.get('/', (req, res) => {
  res.sendFile(__dirname + '/index.html');
});

app.get("/api/html-express", (req, res) => {
  res.send("This is data from Express!");
});

app.listen(PORT, () => {
  console.log("Server is running on port 8080");
});

In this example, the res.sendFile method is used to send the contents of index.html to the client.

3. Usage Example

To test the endpoint, you can make a request to /api/html-express, and the server will respond with the data as a plain string.

fetch("/api/html-express")
  .then(response => response.text())
  .then(data => console.log(data));

The above code makes a fetch request to /api/html-express and logs the plain text data to the console.

3.1 Additional Usage Example

The following example displays the message fetched from the Express server:

This is data from express !
Back

Git Terminal

Arrow