问题
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