JavaScript Answers

How to route all requests to index.html with Node Express?

Spread the love

To route all requests to index.html with Node Express, we call the sendFile method.

For instance, we write

const express = require("express");
const server = express();

server.use("/public", express.static(__dirname + "/static-files-dir"));

server.get("/some-route", (req, res) => {

server.get("/*", (req, res) => {
  res.sendFile(__dirname + "/index.html");

const port = 8000;
server.listen(port, () => {
  console.log("server listening on port " + port);

to create a catch route by calling server.get with '.*'.

And then we call sendFile with the path of index.html to render that as the response.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.