Chris
Chris

Reputation: 1349

NodeJs Express Server to Proxy and Host Static Content

I am trying to create a nodejs server with expressjs that serves my static react content. How do I implement to say if you are a proxied path, proxy else return index.html. Current code is below:

const path = require('path');
const express = require('express');
const app = express();
const publicPath = path.join(__dirname, 'build');
var proxy = require('http-proxy-middleware');

app.use(express.static(publicPath));

app.use('/pcs', proxy('/pcs',
    {
      target: '<target>',
      changeOrigin: true,
      pathRewrite: {'^/pcs': ''},
      hostRewrite: 'localhost:3000',
      protocolRewrite: 'http'
    }));

app.get('*', (req, res) => {
  res.sendFile(path.join(publicPath, 'index.html'));
});

app.listen(3000, () => {
  console.log('Server is up!');
});

Upvotes: 3

Views: 932

Answers (1)

Nick Gagne
Nick Gagne

Reputation: 130

You'll want to use a pattern for matching the proxy path, otherwise it will only match the exact "/pcs" path. Here is a pattern to match any route starting with "/pcs/" (in addition to just "/pcs"):

app.use('/pcs/?*', proxy('/pcs', 
  {
    target: '<target>',
    changeOrigin: true,
    pathRewrite: {'^/pcs': ''},
    hostRewrite: 'localhost:3000',
    protocolRewrite: 'http'
  }));

Upvotes: 1

Related Questions