Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve 404 status when route is not found. Angular 6+ and Universal

I have released my project using Universal and specified in .htaccess that all requests should go to index.html (root page of the Angular application)

as it was asked here: https://angular.io/guide/universal

it allows sharing a link and to open a component specified in a URL

Also, created a component in case if an incorrect route is opened: Handling 404 with Angular2

export const routes:RouterConfig = [
  ...Routes,
  // Show the 404 page for any routes that don't exist.
  { path: '**', component: Four04Component }
];

The problem is that search engines treat the Four04Component as a simple page with 200 OK status rather an error page. Do you know how can retrieve a 404 error together with the Four04Component?

like image 245
Denis Evseev Avatar asked Apr 23 '19 13:04

Denis Evseev


1 Answers

You have to inject Response into your angular app , to achieve that first change these lines in your server.ts :

app.get('*', (req, res) => { //you can find these line easily
res.render('index', {
    req: req,
    res: res,
    providers: [
        {
            provide: REQUEST, useValue: (req)
        },
        {
            provide: RESPONSE, useValue: (res)
        }
    ]
    });
});

Then in your Four04 component inject response like this :

constructor(@Optional() @Inject(RESPONSE) private response: Response,
            @Inject(PLATFORM_ID) private platformId: Object) {}

After that simply try something like this on ngoninit of Four04 component :

ngOnInit(){
    if(isPlatformServer(this.platformId)){
        this.response.status(404);
    }
}

Hope these help someone.

like image 154
Mohammad Reza Avatar answered Oct 13 '22 03:10

Mohammad Reza