Search code examples
angularrouterangular-routingrouterlink

Angular 4 - Routing issue , added a new route and it looks like others, but on page refresh it throws 404 error


On the terminal on my localhost i can see npm say " 404 error /coins"

Then On the page it says Not Found

These URLS work fine

 http://localhost:8808/events/new
 http://localhost:8808/events

But I ADDED in this "coins" one

Go there

http://localhost:8808/coins

Refresh is problem

navbar.component.html

    <li>
      <a [routerLink]="['/coins']">All Coins</a>
    </li>
    <li>
      <a [routerLink]="['/events']">All Events</a>
    </li>
    <li><a [routerLink]="['/events/new']">Create Event</a></li>

Then routes.ts

export const appRoutes:Routes = [
{ path: 'events/new', component: CreateEventComponent },  // process this first , since we have events/:id
{ path: 'events', component: EventsListComponent },
{ path: 'events/:id', component: EventDetailsComponent },
{ path: 'coins', component: CoinsListComponent },
{ path: '', redirectTo: '/events', pathMatch: 'full'}

]

index.html

 <base href="/">

So everything was working until adding this coins... and doing a page refresh , even a hard refresh.

  1. This is not Angular 1 (angularJS ) this is 100% the angular latest 4.0 version with the import { Routes } from '@angular/router'

What could be the problem ?

Update: showing Coin component

import { Component, OnInit } from '@angular/core'
import { CoinService } from './coin.service'

@Component({
    template: `
    <div *ngFor="let coin of coinsList">
     abc
     </div>
    `
})
export class CoinsListComponent implements OnInit {
    coinsList:any[]
    constructor(
        private coinService: CoinService
    ){
    }

    ngOnInit() {
        console.log('oninit coins')
        this.coinsList = this.coinService.getAllCoins()
    }
}

Solution

  • What are you using server side? ExpressJS? If so seems that you haven't setup something like

    server/server.ts

    const app: Application = express();
    
    app.route('/api/coins/').get(coinsRoute);
    

    server/coinsRoute.ts

    export function coinRoute(req, res) {
    
    res.status(200).json({ ...
       });
    }
    

    And you have a tab running the Express server as well as the app in another tab in your console.