I use https://github.com/angular-ui/ui-router library. When I try to access index route (\'/\') I\'m redirected to 404. The code:
angular.module(\'cr\').config(f
You've declared how to behave when any unknown/other route is provided - go to /404
.
But we also have to define how to behave, when some expected, but not "exact" / "not known" route is accessed, ie. create alias
That's where the .when()
could/should be used:
...
// the known route, with missing '/' - let's create alias
$urlRouterProvider.when('', '/');
// the unknown
$urlRouterProvider.otherwise('/404');
Here by example:
// the known route, with missing '/' - let's create alias
$urlRouterProvider.when('', '/');
// Redirect any unmatched url to 404 view (without change location.hash)
$urlRouterProvider.otherwise(function($injector) {
var $state = $injector.get('$state');
$state.go('404', null, {
location: false
});
});
$stateProvider
// homepage views
.state('homepage', {
url: "/",
templateUrl: "views/homepage.html",
data: {
pageTitle: 'Home'
}
... more here ...
})
// 404 views
.state('404', {
url: "/404",
templateUrl: "views/404.html",
data: {
pageTitle: '404 Not found'
}
});
The simplest way for me with ui-router was giving the url field an empty value :
$stateProvider
.state('home', {
url: '',
templateUrl: 'views/homepage.html',
controller: 'AppCtrl'
})
There is nothing wrong with your code. You are just missing an explicit state for 404. Try adding this:
.state('404', {
url: '{path:.*}',
templateUrl: 'views/404'
});
To get rid of the hash (#) symbol you need to inject one more dependency into your config module:
$locationProvider
And use the .html5Mode() method to set HTML5 Mode to true, like so
$locationProvider.html5Mode(true);
Also, ensure your server is configured to allow Angular to handle your routing. For example, here is a Node/Express configuration that allows the above technique to work:
app.get('*', routes.index);
And in your index.js file (or however you configure your node.js instance):
exports.index = function(req, res){
res.render('index');
};