Mironline
Mironline

Reputation: 2799

Combining backend (Express) and frontend (Angular) routes

I want to host the Angular app and its backend in one host (I am not sure if this is a good idea!).

I created a web folder in a NodeJS (express) app and moved the angular deployed file there. Additionally, I made this folder static to make assets available to the public.

All the backend's APIs routes also start with /API/v1/*

When I open the home (index.html), the angular' SPA works perfectly and I can navigate between routes easily, but when I try to open any frontend routes in a new tab, the express can not handle that request.

Any best practices that anyone can share for this scenario would be appreciated.

Upvotes: 2

Views: 489

Answers (1)

Eldar
Eldar

Reputation: 10790

Well, an approach like this may work for your scenario :

  1. Create a catch-all route in your express js. (Which means if it doesn't hit any routes defined, this route will catch it)
  2. In this handler redirect it to the index.html route by adding some context (Like attaching the target url as a query string)
  3. In your angular root page catch this query string and navigate to the target angular page

Which may look like this :

Express route

const url = require("URL");

app.get('*', function (req, res) {
    res.redirect(url.format({
       pathname:"/", // assuming that index.html lies on root route
       query: {
          "navigateTo": req.url,
        }
     }));
})

Angular app root component

// assuming this is the root component
@Component({ ... })
export class AppComponent implements OnInit {

  constructor(private route: ActivatedRoute, private router: Router) { }

  ngOnInit() {
    this.route.queryParams
      .subscribe(params => {
        const { navigateTo } = params;
        if (navigateTo)
        {
            this.router.navigateByUrl(navigateTo);

        }
      }
    );
  }
}

Upvotes: 1

Related Questions