0

I have an Express app set up with has this routing configuration:

app.use(express.static(path.join(__dirname, '../angular-app/dist')));
app.use('/', 
  express.Router().get('/', function(req, res, next) {
    res.redirect('index.html');
  })
);
app.use('/v1', v1); // these are my API routes

If I launch this express app and navigate (in a browser) to its root, the Angular app comes up, but if I navigate to any of the routes within the Angular app, e.g. /mycomponent/ I get the 404 route rendering from Express.

What I want to have happen is that any route that doesn't start with /v1 is delegated to the angular app, and otherwise my API is served. Is this not a sound way of thinking about how to deploy this pair of applications?

To compound this, I have this hosted on an Apache server using a reverse proxy configuration.

   <Location /myapp>
      ProxyPass http://127.0.0.1:3000
      ProxyPassReverse http://1127.0.0.1:3000
   </Location>

... and of course my angular app has <base href="/myapp/"/> in its index.html template to support this. So I'm wondering if the only way to do this "correctly" is to use the reverse proxy for the Express app and have it only serve the API routes, then use some kind of mod_rewrite configuration in Apache to host the Angular app directly from Apache. What do you think?

2
  • try app.get('*', function(req, res, next) { res.sendFile(path.join(__dirname, '../angular-app/dist/index.html')); }); Commented Feb 7, 2018 at 17:03
  • @ChauTran yes, that was super easy thanks! Turn it into an answer and I'll accept it. I literally copy-pasted your suggestion after the `app.use('/v1;, v1) line above. Commented Feb 8, 2018 at 0:59

1 Answer 1

2
app.get('*', function(req, res, next) {
    res.sendFile(path.join(__dirname, '../angular-app/dist/index.html'));
});

Put the above code block before your routes middlewares.

The reason is Angular is a SPA which means it has to load the index.html with all the corresponding *.js and in one of those *.js, there's your RouterModule with your defined Routes. At the point you navigate to another route by typing in the domain/route, or refresh on domain/route which is not the root, index.html hasn't been loaded yet. Thus, the browser is not aware of your Routes definition from Angular.

Sign up to request clarification or add additional context in comments.

Comments

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.