Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle angular2 route path in Nodejs?

I am working on a NodeJS app with Angular2. In my app, I have a home page and search page. For home page I have an HTML page that will render for the localhost:3000/ and from home page user navigate to search i.e localhost:3000/search page that I handled by angular2 routes.

I don't have the page for the search page its view render by the angular2. But when I directly hit localhost:3000/search as I don't have this routing in my node app it gives the error.

I don't know How to handle this in node app?

like image 503
Rhushikesh Avatar asked Jan 18 '16 05:01

Rhushikesh


2 Answers

If you enter localhost:3000/search directly in the browser navigation bar, your browser issues an request to '/search' to your server, which can be seen in the console (make sure you check the 'Preserve Log' button).

Navigated to http://localhost:3000/search

If you run a fully static server, this generates an error, as the search page does not exist on the server. Using express, for example, you can catch these requests and returns the index.html file. The angular2 bootstrap kicks-in, and the /search route described in your @RouteConfig is activated.

// example of express()
let app = express();
app.use(express.static(static_dir));

// Additional web services goes here
...

// 404 catch 
app.all('*', (req: any, res: any) => {
  console.log(`[TRACE] Server 404 request: ${req.originalUrl}`);
  res.status(200).sendFile(index_file);
});
like image 131
user3636086 Avatar answered Oct 12 '22 15:10

user3636086


You need to use HashLocationStrategy

import { LocationStrategy, HashLocationStrategy } from "angular2/router";
bootstrap(AppComponent, [
 ROUTER_PROVIDERS,
 provide(LocationStrategy, { useClass: HashLocationStrategy })
]);

In your bootstrap file.

If you want to go with PathLocationStrategy ( without # ) you must setup rewrite strategy for your server.

like image 30
Vlado Tesanovic Avatar answered Oct 12 '22 16:10

Vlado Tesanovic