Skip to content

Instantly share code, notes, and snippets.

@sinchang
Created May 31, 2018 04:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sinchang/016152c248e266c5cad07eea960820ad to your computer and use it in GitHub Desktop.
Save sinchang/016152c248e266c5cad07eea960820ad to your computer and use it in GitHub Desktop.
Created by gist-it (https://github.com/egoist/gist-it)
'use strict'
/**
* https://github.com/Rokid/NextForum/blob/master/server.js
*/
const fs = require('fs')
const path = require('path')
const https = require('https')
const app = require('express')()
const targetHost = process.env.API_URL
app.use('/api/*', (req, res) => {
var options = {
host: targetHost,
method: req.method,
path: '/api/v1/' + req.params[0],
headers: {
...(req.headers),
host: targetHost,
}
}
const proxyRequest = https.request(options, (proxyResponse) => {
for (let name in proxyResponse.headers) {
res.setHeader(name, proxyResponse.headers[name])
}
res.status(proxyResponse.statusCode)
proxyResponse.pipe(res, { end: true })
})
req.pipe(proxyRequest, { end: true })
})
app.get('/*.:ext', (req, res) => {
const name = req.params[0]
const ext = req.params.ext
const file = fs.createReadStream(
path.join(__dirname, `./dist/${name}.${ext}`))
if (ext === 'js') {
res.set('Content-Type', 'text/javascript');
}
file.on('error', (err) => {
res.status(404)
res.end(err.message)
})
file.pipe(res)
})
app.get('*', (req, res) => {
const html = fs.createReadStream(
path.join(__dirname, './dist/index.html'))
res.type('html')
html.pipe(res)
})
app.listen(process.env.PORT || 8080)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment