Last active
January 8, 2020 01:08
-
-
Save prodrammer/3edab83929b2f46945c29f1145921821 to your computer and use it in GitHub Desktop.
Custom static file server + reverse proxy with clean HTML5 SPA routing support.
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 fs = require('fs') | |
const url = require('url') | |
const path = require('path') | |
const http = require('http') | |
const static = require('node-static') | |
const httpProxy = require('http-proxy') | |
const file = new static.Server('./', { cache: 0 }) | |
const proxy = httpProxy.createProxyServer({}) | |
const server = http.createServer(function(req, res) { | |
// requests beginning with /api should be proxied | |
if (req.url.startsWith('/api')) { | |
proxy.web(req, res, { target: process.env.API_HOST }) | |
return | |
} | |
const urlParts = url.parse(req.url) | |
const filePath = path.join(__dirname, urlParts.pathname) | |
fs.exists(filePath, exists => { | |
if (exists) { | |
file.serve(req, res) | |
return | |
} | |
file.serveFile('/index.html', 200, {}, req, res) | |
}) | |
}) | |
console.log(`hosting app at http://localhost:${process.env.PORT}`) | |
console.log(`proxying /api to ${process.env.API_HOST}`) | |
server.listen(process.env.PORT) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
npm i node-static http-proxy -D
Needs
PORT
(i.e. 8000) andAPI_HOST
(i.e. http://my-api-server.com) environment variables.