Last active
July 24, 2020 21:26
-
-
Save wenheqi/be6747d4bcf85523e4a00fa43f272658 to your computer and use it in GitHub Desktop.
Serve front-end web pages and backend APIs under the same URL
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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