简体   繁体   中英

Routing in angular2 Not Working In live server

I have built a website using angular2, it works fine on localhost but when i deploy it on my server all css and js links appears broken.

ex:localhost:4200/home works fine but ip:4200/home gives 404 for css and js files.

ip:4200 itself redirects to home but typing ip:4200/home gives 404 even on reload it gives 404

I think i need to fix the routing for these.

My router ts file is as follows:

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


import { HomeComponent }  from './component/home.component';
import { RegisterComponent } from './component/register.component';
import { ProductComponent } from './component/product.component';

const appRoutes: Routes = [

  {
    path: '',
    redirectTo: '/home',
    pathMatch: 'full'
  },

  {
    path: 'home',
    component: HomeComponent
  },
  {
   path: 'register',
   component: RegisterComponent
  },
   {
    path: 'product',
    component: ProductComponent
  }


];

export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);

and app.module.ts is like this:

import { NavBar } from './component/nav-bar.component';
import { RegisterService } from './services/register.service';
import { HomeService } from './services/home.service';
import { ProductService } from './services/product.service';
import { ProductComponent } from './component/product.component';
import { NavBar1 } from './component/nav-bar1.component';
@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
    RegisterComponent,
    NavBar,
    ProductComponent,
    NavBar1

  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    RouterModule.forRoot([
         {
           path: 'register',
           component: RegisterComponent
         }
       ]),

    routing
  ],
  providers: [
RegisterService,
HomeService,
ProductService
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Switch to HashLocationStrategy

providers: [{provide: LocationStrategy, useClass: HashLocationStrategy}, ...

or configure your server to support HTML5 pushState (rewrite requests to non-existing files to index.html .

You should include .htaccess and put this code and keep file in root.

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
</IfModule>

i hope i make you day.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM