Nishank Singla
Nishank Singla

Reputation: 949

Angularjs html5Mode(true) page reload error with Node.js Server

I have used routeProvider and stateProvider in Angular js with HTML5 mode true. Everything is working fine until I refresh the page.

I am using Node.js server, I am not getting what to write on server side so that I don't get "Can not find" error.

Please help me with this, I am not getting any answers from other similar posts.

here's the code of state provider

   $stateProvider
  .state("/", angularAMD.route({
    url: '/',
    templateUrl: 'Default/default.html'
  }))
  .state("aboutUs", angularAMD.route({
    url: '/aboutUs',
    templateUrl: 'AboutUs.html'
  }))
  .state("contactUs", angularAMD.route({
    url: '/contactUs',
    templateUrl: 'ContactUs.html'
  }))
  .state("order", angularAMD.route({
    url: '/order',
    templateUrl: 'order/order.html',
    controllerUrl: "order/OrderController"
  }))
  .state("signin", angularAMD.route({
    url: '/signin',
    templateUrl: 'LoginSignup/Login.html',
    controllerUrl: "LoginSignup/LoginController"
  }))
  .state("dashboard", angularAMD.route({
    url: '/dashboard',
    templateUrl: 'Dashboard/dashboard.html',
    controllerUrl: "Dashboard/dashboardController"
  }))
  .state("thankYou", angularAMD.route({
    url: '/ThankYou.html',
    templateUrl: 'ThankYou.html'
  }));
$urlRouterProvider.otherwise("/");
$locationProvider.html5Mode(true);

Upvotes: 1

Views: 1627

Answers (2)

pizzarob
pizzarob

Reputation: 12059

You will need to load your index file with your angular code on refresh, like Joe Lloyd said. In order to allow your other routes to work (the routes that return data) you can check for them and call the next function if it is a match. Here is an example:

app.use((req, res, next) => {

    // if the requested route matches a route that should return data then
    // we check for it here and call the next function and return, which will skip over serving the index.html page
    if(req.url.indexOf('/get-data-route')){
        return next();
    }

    // if the route does not match an API route serve the index file
    // this is using a template string, if you are using an older version of node
    // replace the template string with a regular string
    res.sendFile(`${__dirname}/index.html`);
});

Upvotes: 0

Joe Lloyd
Joe Lloyd

Reputation: 22513

Use the following snippet in Express

I fixed my app with this in Express.js on the nodejs server.

// ### CATCH REFRESH TO INDEX ###
app.all('/*', function(req, res, next) {
  // Just send the index.html for other files to support HTML5Mode
  res.sendFile('public/index.html', { root: __dirname });
});

it looks in the correct place for the page refresh.

Upvotes: 4

Related Questions