3

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!');
});
3
  • just a side note: you are much better off doing this with a web server instead of node.js and express Commented Aug 16, 2019 at 2:50
  • 1
    @TuanAnhTran by web server do you mean something like an nginx reverse proxy? Commented Aug 16, 2019 at 2:53
  • yeah, like nginx reverse proxy Commented Aug 18, 2019 at 14:42

1 Answer 1

1

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'
  }));
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the reply, even with that change calls to /pcs/* are still returning the static content and not the expected content from the target server.
This is working correctly for me locally. What URL are you testing with, which is not being sent to the proxy?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.