[英]angular parses url with LocationHashbangUrl but $locationProvider.html5Mode(true) is set
[英]Angular - $locationProvider.html5Mode(true) prevents otherWise method for routeProvider
我遇到一個問題,只要我廣告$ locationProvider.html5Mode(true); 到我的應用程序,它不再遵循routeProvider中定義的otherWise方法。 與其返回404頁面,不如顯示一個錯誤頁面:
無法獲取/ myWrongURL
app.js
angular
.module('myApp', [
'ngAnimate',
'ngCookies',
'ngResource',
'ngRoute',
'ngSanitize',
'ngTouch'
])
.config(function ($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl',
controllerAs: 'main'
})
.when('/about', {
templateUrl: 'views/about.html',
controller: 'AboutCtrl',
controllerAs: 'about'
})
.when('/projects', {
templateUrl: 'views/projects.html',
controller: 'ProjectsCtrl',
controllerAs: 'projects'
})
.when('/contact', {
templateUrl: 'views/contact.html',
controller: 'ContactCtrl',
controllerAs: 'contact'
})
.otherwise({
redirectTo: '404.html'
});
// use the HTML5 History API
$locationProvider.html5Mode(true);
});
我使用Yeoman角度模板來搭建我的應用程序,目前幾乎所有東西都已開箱即用,除了我設置的量角器測試。
我認為,訊息
無法獲取/ myWrongURL
是服務器問題。
角度$ location html5模式僅解決客戶端設置-url不包含#,位置控件也包含URL中的路徑部分。
HTML5模式需要服務器端配置。 每個請求都必須返回應用程序入口點-通常為index.html。 您的服務器通過路由路徑搜索文件,而不是返回索引-這就是您看到錯誤的原因。
這是grunt服務器的問題(謝謝@milanlempera)。 對於任何尋求解決方案的人,我都在Kryx 在這里回答自己的問題時找到了它。
如果還有其他人偶然發現此問題,請解決以下問題:
(添加的唯一行是modRewrite行)
livereload: {
options: {
open: true,
middleware: function (connect) {
return [
modRewrite(['^[^\\.]*$ /index.html [L]']),
connect.static('.tmp'),
connect().use(
'/bower_components',
connect.static('./bower_components')
),
connect.static(appConfig.app)
];
}
}
},
確保在grunt文件的頂部聲明了以下內容:
var modRewrite = require('connect-modrewrite');
我唯一能做的就是您需要通過npm安裝modrewrite,如下所示:
npm install connect-modrewrite --save-dev
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.