There's more...

If you want to send static files for some specific reason, without using the method shown in the preceding section, you can use routing and the res.sendFile() method, as shown in the following code:

// Source file: src/serve_statics_alt.js

/* @flow */
"use strict";

const express = require("express");
const app = express();
const path = require("path");

const flagsPath = path.join(__dirname, "../flags");

app.get("/uruguay", (req, res) =>
res.sendFile(`${flagsPath}/america/south/UY.png`)
);

app.get("/england", (req, res) =>
res.sendFile(`${flagsPath}/europe/GB.png`)
);

app.get("/license", (req, res) =>
res.sendFile(`${flagsPath}/license.txt`)
);

app.use((err, req, res, next) => {
console.error("Error....", err.message);
res.status(500).send("INTERNAL SERVER ERROR");
});

app.listen(8080, () =>
console.log(
"Mini Express static server ready at http://localhost:8080/!"
)
);

If you access http://127.0.0.1:8080/uruguay, you'll get my home country's flag, and http://127.0.0.1:8080/license will retrieve the MIT license for the icon set I chose; see the latter in the following screenshot:

 Testing a different route that sends back a text file

Of course, you wouldn't use this method if you had lots of static files to provide, but if you have only a few, then this alternative solution works very well.

You may have noticed that I didn't add headers for caching, but it can certainly be done. Read more on res.sendFile() at https://expressjs.com/en/api.html#res.sendFile, in particular the immutable and headers options.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.12.162.179