Search code examples
angular-routingangular8

Angular Routing - Direct path access not working from URL


I created and host www.xinthose.com. This is the source code for the website. When you navigate to the website, it will take you to the path /home, but when you try to duplicate that tab or go directly to www.xinthose.com/home, I get a 404 error from HostGater (my website host). This is the contents of app-routing.module.ts:

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

import { HomeComponent }   from './home/home.component';
import { BibleComponent }   from './bible/bible.component';
import { AboutComponent } from './about/about.component';
import { PageNotFoundComponent } from './page-not-found/page-not-found.component';

const routes: Routes = [
  { path: '', redirectTo: '/home', pathMatch: 'full' },
  { path: 'home', component: HomeComponent },
  { path: 'bible', component: BibleComponent },
  { path: 'about', component: AboutComponent },
  { path: '**', component: PageNotFoundComponent },
];
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Why is this happening and how do I fix it? Is it related to pathMatch at all? Am I missing some Route property?


Solution

  • It took me almost a year, but I figured out that you have to pay for node.js hosting, AWS elastic beanstalk is a good candidate for this. Then you have to serve your static compiled website using something like express.js. This is my working example server.js:

    "use strict";
    const express = require("express");
    const compression = require('compression');
    
    // config
    const port = process.env.PORT || 3000;
    const app_folder = "./";
    const options = {
      dotfiles: 'ignore',
      etag: false,
      extensions: ['html', 'js', 'scss', 'css'],
      index: false,
      maxAge: '1y',
      redirect: true,
    }
    
    // create app
    const app = express();
    app.use(compression());
    app.use(express.static(app_folder, options));
    
    // serve angular paths
    app.all('*', function (req, res) {
        res.status(200).sendFile(`/`, {root: app_folder});
    });
    
    // start listening
    app.listen(port, function () {
        console.log("Node Express server for " + app.name + " listening on http://localhost:" + port);
    });
    

    Then in package.json you have a start command the website host will run:

    {
        "name": "xinthose.com",
        "scripts": {
            "ng": "ng",
            "start": "node server.js",
            "build": "ng build",
            "test": "ng test",
            "lint": "ng lint",
            "e2e": "ng e2e"
        },
        "dependencies": {...},
        "devDependencies": {...}
    }