Error 404 when implementing routing in Angular 2 with Auth0

In my Angular 2 application, I am utilizing Auth0 authentication.

While everything works fine on localhost, I encounter issues when running the application on the server (my domain).

Based on what I know, my problem seems to be with the routes.



Issue:

I can successfully log in using Auth0 in my Angular app (both on localhost and on the server - including logout). Post login, the application redirects to my Control Page without any issues, and within the application, I have menus, pages with their respective routes, etc.

Everything functions correctly on localhost, BUT after logging in on the server, I am unable to navigate between the pages in my app. Everything results in a 404 page, even upon refreshing the page.

In addition to this, I am also incorporating JQuery and Materialize CSS. Upon reloading, JQuery fails to load initially but eventually loads after the refresh, making the effects work.



Code:

app.routing.ts:

import { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { AuthGuard } from './auth/auth.guard';

import { HomeComponent } from './components/home/home.component';
import { PainelComponent } from './components/painel/painel.component';
import { ReunioesComponent } from './components/reunioes/reunioes.component';
import { AssociadosComponent } from './components/associados/associados.component';
import { CalendarioComponent } from './components/calendario/calendario.component';
import { TesourariaComponent } from './components/tesouraria/tesouraria.component';
import { DocumentosComponent } from './components/documentos/documentos.component';

const appRoutes: Routes = [
    {
        path: '',
        component: HomeComponent
    },
    {
        path: 'painel',
        component: PainelComponent,
        canActivate: [AuthGuard]
    },
    {
        path: 'associados',
        component: AssociadosComponent,
        canActivate: [AuthGuard]
    },
    {
        path: 'calendario',
        component: CalendarioComponent,
        canActivate: [AuthGuard]
    },
    {
        path: 'reunioes',
        component: ReunioesComponent,
        canActivate: [AuthGuard]
    },
    {
        path: 'tesouraria',
        component: TesourariaComponent,
        canActivate: [AuthGuard]
    },
    {
        path: 'documentos',
        component: DocumentosComponent,
        canActivate: [AuthGuard]
    }
];

export const appRoutingProviders: any[] = [];
export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes, {useHash: false})


auth.service.ts:

import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { tokenNotExpired } from 'angular2-jwt';

declare var Auth0Lock: any;

@Injectable()
export class Auth {
    lock = new Auth0Lock('SECRET', 'SECRET.auth0.com', {});

    constructor(private router: Router) {
        this.lock.on("authenticated", (authResult) => {
            this.lock.getProfile(authResult.idToken, (err, profile) => {
                if(err)
                    throw new Error(err)

                localStorage.setItem('profile', JSON.stringify(profile));
                localStorage.setItem('id_token', authResult.idToken);

                this.router.navigate(['/painel'])
            })
        });
    }

    public login() {
        this.lock.show()
    }

    public authenticated() {
        return tokenNotExpired()
    }

    public logout() {
        localStorage.removeItem('id_token');
        localStorage.removeItem('profile')
    }
}


sidenav.partial.html:

<ul id="slide-out" class="side-nav fixed">
    <li><a href="/associados"><i class="material-icons">group</i>Associados</a></li>
    <li><a href="/calendario"><i class="material-icons">event</i>Calendário</a></li>
    <li><a href="/painel"><i class="material-icons">new_releases</i>Calendário Próximo</a></li>
    <li><a href="/reunioes"><i class="material-icons">forum</i>Reuniões</a></li>
    <li><a href="/tesouraria"><i class="material-icons">monetization_on</i>Tesouraria</a></li>
    <li><a href="/documentos"><i class="material-icons">attach_file</i>Documentos</a></li>
    <li><br></li>
    <li class="show-on-med-and-down hide-on-large-only">
         <a href="#!" (click)="auth.logout()"><i class="material-icons">close</i>Sair</a>
    </li>
</ul>



Thanks!

Answer №1

When setting up Auth0 in my ng2 application, I encountered a similar issue as yours regarding routing. The solution lies in how you configure your routing mechanism. To resolve this problem, you will need to implement HashLocationStrategy. Simply include the following snippet in the providers array within your app.module.ts:


 {
   provide: LocationStrategy,
   useClass: HashLocationStrategy
 },

After making this adjustment, refer to the guide linked below for detailed instructions on correctly incorporating hash routing with Auth0 (consider workaround #2 if using a more recent version of ng2):

Utilizing the HashLocationStrategy with the Auth0 Lock widget for user login

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

How can I transfer an instance of a class to dataTransfer.setData?

So I created a new instance of a class: let item = new Item(); Next, I attempted to serialize the item and add it to dataTransfer for drag and drop functionality: ev.dataTransfer.setData("info", JSON.stringify(item)); At some point, I need to retriev ...

Issue with absolute import in React TypeScript application

An error occurs when trying to import a module, displaying the following message: Compiled with problems: × ERROR in ./src/App.tsx 5:0-33 Module not found: Error: Can't resolve 'routes' in 'F:\Tamrinat\Porfolio\microsite ...

Encountering Error ENOENT while running Gulp Build Task with SystemJS in Angular 4

UPDATE: 2020.02.13 - It seems like another individual encountered the same issue, but no solution was found. Check out Github for more details. An array of GulpJS errors is emerging when attempting to construct an Angular 4 Web App with SystemJS. The str ...

Why is it necessary for me to manually include and configure all d3.js dependencies in the SystemJS config file?

Currently, I am utilizing the systemjs.config.js file for an Application built on Angular5.x. To implement DAG charts in the application, I installed npm install --save @swimlane/ngx-graph and npm install --save @swimlane/ngx-charts. I have set up a comp ...

Tips for effectively combining the map and find functions in Typescript

I am attempting to generate an array of strings with a length greater than zero. let sampleArray2:string[] = ["hello","world","angular","typescript"]; let subArray:string[] = sampleArray2 .map(() => sampleArray2 .find(val => val.length & ...

Tips for customizing the `src/app/layout.tsx` file in Next.js 13

I am looking to customize the layout for my /admin route and its child routes (including /admin/*). How can I modify the main layout only for the /admin/* routes? For example, I want the / and /profile routes to use the layout defined in src/app/layout.ts ...

I encountered TS2300 error stating a duplicate identifier appeared once I transferred my code to Angular CLI

Currently undergoing the process of transitioning our code to Angular CLI for our hybrid app. The plan is to migrate the Angular part to CLI while the AngularJS portion continues to be handled by custom Webpack. It's worth noting that both parts (Angu ...

The switchMap function is sending back a single item

I'm having an issue with switching the observable using the switchMap operator: return this.db.list(`UserPlaces/${this.authData.auth.auth.currentUser.uid}`, { query: { orderByChild: 'deleted', equalTo: false } }) .ma ...

Creating a mat-tree component in Angular Material 6.0.1: Step-by-step guide

I am encountering an issue with my material angular mat-tree based application. The code runs without errors, but the values are not displayed on the screen. I need help resolving this problem so that I can proceed with the development. Upon opening the a ...

Incorporating Copyleaks SDK into Angular: A Seamless Integration

Currently, I'm in the process of implementing the Copyleaks SDK with Angular to conduct plagiarism checks on two text area fields within an HTML form. Within the form, my goal is to incorporate two buttons: one to check for plagiarism on one text area ...

Accessing an unregistered member's length property in JavaScript array

I stumbled upon this unique code snippet that effectively maintains both forward and reverse references within an array: var arr = []; arr[arr['A'] = 0] = 'A'; arr[arr['B'] = 1] = 'B'; // When running on a node int ...

The issue arises when trying to pass multiple parameters with the Angular 2 router and encountering

After creating a sample Plunker to pass multiple parameters to the next page, I encountered an issue where the crisis center routing failed to work properly upon clicking on items. See the demonstration on Plunker here: http://plnkr.co/edit/ngNSsKBzAuhaP0E ...

Perform validation on input by monitoring checkbox changes in Angular 4

I am currently working on a project where I need to loop through an array of key values in order to create a list of checkboxes, each accompanied by a disabled input field as a sibling. The requirement is that upon checking a checkbox, the corresponding in ...

Building a NestJS/Prisma RESTful API to retrieve data from a related field

I am diving into creating my very own Rest API using Nestjs and Prisma for the first time. This project is a basic representation of an inventory management system, keeping things simple with shelves and boxes to store items. The structure in place has tab ...

ReactJS Typescript Material UI Modular Dialog Component

Hello, I need help with creating a Reusable Material UI Modal Dialog component. It's supposed to show up whenever I click the button on any component, but for some reason, it's not displaying. Here's the code snippet: *********************TH ...

There is an issue with the target entry-point "fullcalendar/angular" as it is missing some dependencies

My current project uses Ionic, but I'm encountering an error related to missing dependencies for "@fullcalendar/angular" when running ionic serve. Error: [ng] ERROR in The target entry-point "@fullcalendar/angular" has some missing dependencies ...

`How can we efficiently transfer style props to child components?`

Is there a way to pass Props in the Style so that each component has a unique background image? Take a look at this component: countries.astro --- import type { Props } from 'astro'; const { country, description } = Astro.props as Props; --- & ...

The code encountered an issue with TS2554 error, as it was anticipating two arguments but was only provided with one when

Before, I utilized ViewChild like this: @ViewChild("InternalMedia") localStream; @ViewChild("emoji") mEmoji; Everything was functioning well up until angular-7.x. However, after updating to angular-8.x, the following error started popping up: .../call_ ...

A deep dive into TypeScript: enhancing a type by adding mandatory and optional fields

In this scenario, we encounter a simple case that functions well individually but encounters issues when integrated into a larger structure. The rule is that if scrollToItem is specified, then getRowId becomes mandatory. Otherwise, getRowId remains option ...

Encountering NullInjectorError while testing Angular unit tests: DatePipe provider is missing

I have been working on implementing unit tests for a service that has dependencies injected from two other services. One of the injected services utilizes the Angular DatePipe, so I am utilizing the Angular TestBed to automate the process. However, when ru ...