Cannot GET - Error After refresh using Ionic

喜夏-厌秋 提交于 2021-01-28 12:14:05

问题


I'm using Ionic framework to build a hybrid mobile application and I have html5Mode set to true, Ui-Router, and gulp to provide me with livereload, sass compiling, css and javascript minifying.

The problem is whenever I navigate to a state directly from the index, everything works fine, requests are being made to my server, but when I refresh that same state, I get Cannot GET error.

I am treating my Ionic application as a separate thing from my Express.JS app.

Here's some code:

States

 $stateProvider

 .state('faculties', {
    url: '/',
    templateUrl: 'views/main/main.html',
    controller: 'MainCtrl as main'
  })

  .state('faculty', {
    url: 'faculties/:faculty',
    templateUrl: 'views/faculty/faculty.html',
    controller: 'FacultyCtrl as v'
  })

So, if I opened the page and clicked on the button that takes me to the 'faculty' state, It's all good. But if I refresh that page, it's giving me that Cannot GET error. Here's the code from the 'faculty' state controller:

  app.controller('FacultyCtrl', function ($http, $stateParams, appConfig) {

  var v = this;
  var api = appConfig.api;
  v.faculty = {};

  $http.get( api + '/faculties/' + $stateParams.faculty)
  .then( res => {
    v.faculty = res.data;
  }).catch( error => {
    console.log(error);
  });

});

回答1:


The problem you are having is that you do not route all possible urls to the same index.html

When you first load the page, say, the URL being http://example.com/, your web server will serve the static file index.html from your root. When changing the route, your URL ends up as (for example) http://example.com/some_page. This works because the URL is "faked", there is no such file on the server. When refreshing (or going to that URL directly), that URL is requested from the server, which fails (since, as before, that file/folder does not exist).

What you need to do is route all requests (excluding API and whatnot) to the same static index.html, this is standard behavior of all single-page apps: The routing is done clientside.



来源:https://stackoverflow.com/questions/35117884/cannot-get-error-after-refresh-using-ionic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!