The Angular URL functions perfectly on localhost:4200, but encounters issues in the build project

After developing my project locally, the sub URLs like http://localhost:4200/login work fine. But once I build the project using ng build --prod, all sub URLs stop functioning on the live server.

When I navigate to a sub URL using

this.router.navigate(['/system']);
it works in the built project, but upon reloading the same URL, it results in a 404 error.

Could this be an issue with my Routing Strategies?

index.html

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8>
  <title>title</title>
  <base href="/">
</head>
<body>

  <app-root></app-root>

</body>
</html>

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from "@angular/forms";
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HomeComponent } from './components/home/home.component';
import { HttpClientModule } from "@angular/common/http";
import { SystemComponent } from './components/system/system.component';
import { RouterModule, Routes } from '@angular/router';
import { AdminComponent } from './components/admin/admin.component';

const appRoutes: Routes = [
    { path: '', component: HomeComponent }, // home pages
    { path: 'login', component: HomeComponent },// sub page 1
    { path: 'system', component: SystemComponent }, // sub page 2
    { path: 'admin', component: AdminComponent }//sub page 3
];

@NgModule({
    declarations: [
        AppComponent,
        HomeComponent,
        SystemComponent,
        AdminComponent
    ],
    imports: [RouterModule.forRoot(
        appRoutes,
        { enableTracing: true },// <-- debugging purposes only it will show  big  console  log  data
        { useHash: true } ),
        BrowserModule,
        AppRoutingModule,
        FormsModule,
        HttpClientModule
    ],
    providers: [],
    bootstrap: [AppComponent]
})
export class AppModule {
}

Answer №1

Make sure that the base href is correctly configured in your index.html

If needed, you can utilize the following commands to adjust them:

ng build --base-href /

or ng build --bh /

or ng build --prod --bh /

This will replace the existing base href defined in index.html and establish it if absent. Adapt it based on your deployment requirements. I cannot provide specific advice without knowing your deployment approach.

You might also want to explore the --deploy-url option if your assets are stored in a separate folder refer [ ]

Answer №2

After much searching, I finally uncovered the solution to my error - it was related to my .htaccess file. These are the resources that guided me in resolving this issue.

HOWTOs / Making sure .htaccess and mod_rewrite are working as they should

  • To update your virtual host files, open
    sudo nano
    /etc/apache2/sites-available/000-default.conf
  • Add the following code under DocumentRoot /var/www/html

    <Directory /var/www/html/projectFolder>
       # Don't show directory index
       Options -Indexes +FollowSymLinks +MultiViews
          
       # Allow .htaccess files
        AllowOverride All
          
       # Allow web access to this directory
       Require all granted
    </Directory>

  • Lastly, don't forget to restart the server.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the best practices for utilizing the error prop and CSS with the Input API in Material UI while utilizing context

When working with the MUI Input API props and CSS, I encountered an issue related to the {error} and its use. This is how my code looks: const [value, setValue] = useState<string>(cell.value); const [startAdornment, setStartAdornment] = useState< ...

What is preventing me from manipulating this Object outside of the ngOnInit() function?

I've been working on a project that involves fetching data from the server and manipulating it within the .ts file. However, I seem to be facing a common issue related to Typescript/angular concepts that I'm struggling to grasp...I would really a ...

What's the best approach for implementing typescript in a Vue.component?

Recently, I came across a utility function within my Vue component that resets all data content. export function resetData(vm: any) { Object.assign(vm.$data, vm.$options.data.call(vm)); } I would like to remove the "any" type from my Vue component. Is ...

What is the best way to incorporate an interface in TypeScript that is both callable and has properties?

Given the scenario where an interface is defined as: interface FooWithBar { ():void; bar():void; } I am struggling with writing the implementation. I attempted the following: function foo(){ } foo.bar = function(){ }; This approach did not wo ...

Issue concerning the Bootstrap version, transitioning from Bootstrap 3 to Bootstrap 4

Upon initially installing bootstrap version "bootstrap": "^3.3.7",, everything was functioning properly, except for the inability to utilize a card component. For example: <div class="card" style="width: 18rem;"> <img class="card-img-top" src= ...

Create a CRUD interface in Angular 5 using automated generation techniques

Is there a framework available that can assist in creating CRUD view files from a database table within an MVC project, with Angular as the front-end? I have spent hours searching on Google but still haven't found a solution. All I came across were i ...

Challenges with migrating Kendo Data Grid to Angular 14

While using the Kendo grid for Angular, I encountered the following error after upgrading to Angular 14 and updating the packages in the package.json file. Could this issue be related to the package versions? TypeError: Cannot read properties of undefine ...

Parsing Devx DataGrid filter object for generating SQL queries

Sharing the solution here in case anyone finds it helpful. This code snippet helps convert the Devx Grid Filters into a group of objects to construct the query. ...

Diving into Angular Typescript: Understanding the [object Object] in HTML

One of my todos requires the following input: todo.ts: import { TodoTag } from "./todo-tag-custom"; export class Todo { ... tags: TodoTag[]; } todo.html <tr *ngFor="let todo of todosFiltered()"> <td>{{todo.tags | json ...

Creating a DynamoDB table and adding an item using CDK in Typescript

Can anyone guide me on how to add items to a Dynamodb Table using CDK and Typescript? I have figured out the partition/sort keys creation, but I am struggling to find a straightforward solution for adding items or attributes to those items. Additionally, ...

CDK Drag and Drop capability for lists within lists

I am trying to figure out how to display users and their corresponding information in a structured way. Each user should be presented in their own column, with the associated information displayed within that column. I have been attempting to drag and drop ...

Configuring the AJAX URL for jQuery in a JS file within an ASP.NET MVC application

Currently, when making an Ajax call to an MVC action, I have my JavaScript code directly within the View instead of in a separate JS file. This makes it very convenient to include the URL in the ajax call using Url.Action(): var xhr = $.ajax({ url: ...

A static factory method within an abstract class

I am currently developing a class system using Typescript. The main structure consists of an abstract class called Component, which includes a static method called create(). This method is utilized on child classes to generate specific instances. abstract ...

Converting Celsius to Fahrenheit using AngularJS

As a beginner in programming, I am eager to create a program similar to the one shown in the image below. https://i.sstatic.net/HvLyH.png In my 'converter.component.html' file, I have written the following code: <html> <head></hea ...

Handling Click and Mouse Events with React [react-sortable-hoc, material-ui, react-virtualized]

I have come across an interesting example that I would like to share with you. Check out this live working example on Stackblitz When the delete button on the red bin icon is pressed, the onClick event handler does not get triggered (sorting happens inst ...

Why does TypeScript not generate an error if props are not passed to a functional component?

How does TypeScript handle not passing down props to a functional component without throwing an error? Consider the following code snippet: interface Props{ id: string; className?: string; } export const Buttons: React.FC<Props> = () => { r ...

Determining the location of an input field in Angular

I am currently utilizing Angular for my project. Within the framework, I have a primary component called name.component.ts/html. By utilizing this base component, I have created four additional components - first-name.component.ts/html, last-name, middle-n ...

Unable to locate debugElement in Angular 2 unit tests

I am currently running unit tests on my component, which serves as an output for the router. I have successfully stubbed the router and service utilized by the component. I am attempting to retrieve the element using fixture.debugElement to verify the func ...

Can a single data type be utilized in a function that has multiple parameters?

Suppose I have the following functions: add(x : number, y : number) subtract(x : number, y : number) Is there a way to simplify it like this? type common = x : number, y : number add<common>() This would prevent me from having to repeatedly define ...

Having trouble with running npm start for the Angular2 QuickStart on Windows 10?

While attempting to replicate the Angular official tutorial for Windows 10 (https://angular.io/guide/quickstart), I encountered an error when running the "npm start" command: 0 info it worked if it ends with ok 1 verbose cli [ 'C:\\Program ...