Kumail Hussain
Kumail Hussain

Reputation: 879

angular2 with node routes issue

I am currently working with angular2 and for deployment purpose I have to use node as my server .I am stuck in the routes

Success Scenario :

if I navigate to pages using routerLink it works fine node serve them well

route is: http://localhost:8080/sign-in --- works fine

Failure Scenario : If I enter address same as above manually in the address bar it couldn't load the page

i.e it stuck saying app-loading that is the index.html and other routes not working

index.js

const express = require('express');
const app = express();
var path = require("path");



app.use(express.static(__dirname + '/dist'));


app.get('/[^\.]+$', function(req, res) {
  console.log(__dirname+'/src/index.html')
  res.sendFile(path.join(__dirname+'/src/index.html'))
});
app.listen(process.env.PORT || 8080);

The issue is with node server that couldn't serve up the pages,but I want routes to work even from the address bar any help will be highly appreciated The app is for production mode with angular 4

Upvotes: 0

Views: 53

Answers (2)

Fasco
Fasco

Reputation: 243

In your angular project:

Don't forger to build your project with ng build. After that, you will see a new directory: dist This directory contains your angular project.

In your node project:

You have to send all the routes in your angular project with that:

// Send all other requests to the Angular app
app.get('*', (req, res) => {
    res.sendFile(path.join(__dirname, 'yourprojectangular/dist/index.html'));
});

Upvotes: 1

Faly
Faly

Reputation: 13356

Try using HashLocationStrategy as LocationStrategy:

import { HashLocationStrategy, LocationStrategy } from '@angular/common';

@NgModule({
    // ...
    providers: [{provide: LocationStrategy, useClass: HashLocationStrategy}],
    // ...
})
export class AppModule {}

Upvotes: 0

Related Questions