Skip to content

Instantly share code, notes, and snippets.

@wenheqi
Last active July 24, 2020 21:26
Show Gist options
  • Save wenheqi/be6747d4bcf85523e4a00fa43f272658 to your computer and use it in GitHub Desktop.
Save wenheqi/be6747d4bcf85523e4a00fa43f272658 to your computer and use it in GitHub Desktop.
Serve front-end web pages and backend APIs under the same URL
const express = require("express");
const path = require("path");
const PORT = process.env.PORT || 5000;
const app = express();
const router = express.Router();
// this middleware function must come before
// express.static middleware
router.use("/", (req, res, next) => {
// Performs access permission check and
// then retrieves JSON data or return
// error message base on user input.
// Following statement simply echo the
// query string back to user.
if (/^\/\?.+/.test(req.url)) {
return res.send(req.query);
}
next();
});
router.use("/", express.static(path.join(__dirname, "public")));
app.use("/", router);
app.listen(PORT, () => {
console.log(`Some magic is happening on port ${PORT}`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment