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) => {
res.send("ok");
});
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.