Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refreshing same URL gives 404 not found in angular

I have hosted my angular application on a server. When I click the server url , it redirects me to login page. However, when I refresh the same url suffixed with login, it gives me 404 not found error. The original url given is without login suffix. Please help.

enter image description here

enter image description here

In app.routing.module.ts, I have configured router paths like this:

enter image description here

like image 417
Sarwan Avatar asked May 11 '26 09:05

Sarwan


1 Answers

This happens with Angular sometimes. There's a few different reasons why this happens that I have seen. One because URL changes happen using simple js, and also to block web crawlers since there is no content on a given link.. Anyways, if you want a quick fix, you can use a hash approach. This approach will make your links look like so: http://link/#/page compared to http://link/page (note the #)

Option 1

In your app.module.ts, add imports for HashLocationStrategy, LocationStrategy:

import { HashLocationStrategy, LocationStrategy } from '@angular/common'; , then in your NgModule Provider:

{provide: LocationStrategy, useClass: HashLocationStrategy}

This could look something like the following:

App.Module.Ts

import { NgModule }       from '@angular/core';
import { BrowserModule  } from '@angular/platform-browser';
import { AppComponent }   from './app.component';
import { HashLocationStrategy, LocationStrategy } from '@angular/common';

@NgModule({
    declarations: [AppComponent],
    imports: [BrowserModule],
    providers: [{provide: LocationStrategy, useClass: HashLocationStrategy}],
    bootstrap: [AppComponent],
})
export class AppModule {}

Option 2

Another way is going to be by using RouterModule.forRoot... with useHash: true arg.

In your routing module or app module:

@NgModule({
  imports: [
    ...
    ...
    RouterModule.forRoot(routes, { useHash: true })
  ],

Option 3

If these don't work, or they don't give you the desired outcome (you may not want the has approach), then I would recommend looking into AngularUniversal, or look into serverside approaches to configure your server to serve the index.html file for each route defined. This is a longer more complex approach, but hopefully the above options will suffice.

like image 173
Jeremy Avatar answered May 13 '26 00:05

Jeremy