Tom O'Brien
Tom O'Brien

Reputation: 1831

AngularJS Routing not working when url typed

So, I'm pretty new to AngularJS and I'm trying to use AngularJs ngRoute in my application.

It all works smoothly when I start at the application homepage:

http://localhost:8080/appName/

And when I click on links from this point it works smoothly.

However, when I type a URL that I know exists/works, it gives me a 404 error. If I go to that link by using the application instead of the url it loads fine, even though it has the same url.

Eg. http://localhost:8080/appName/search 

will give a 404, even though that is the same url that is the default redirect.

Indeed, the only url that will load by typing in the location is the base URL I mentioned above.

My app.js looks like this:

app.config( ['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider){
  $routeProvider
    .when("/search", {
      templateUrl: "search.html",
      controller: "SearchController"
    })
  .when("/results", {
    templateUrl: "results.html",
    controller: "ResultsController"
  })
  .when("/browse", {
    templateUrl: "browse.html",
    controller: "BrowseController"
  })
  .otherwise({redirectTo:"/search"});

//This gets rid of the # on the urls to the templates  
$locationProvider.html5Mode(true);

}]);

I am hosting this on a glassfish4 server.

Is there something obvious I am missing/misunderstanding about how ngRoute works? Is there some setting that I am missing?

All help appreciated...

EDIT 1: As @Matthew Green below says, I need to configure the webserver to return the index.html for all pages below

http://localhost:8080/appName

I know I am being completely dense here, but where abouts is this configured? I am hosting the code in a MAVEN Jersey-Quickstart-Webapp.

Upvotes: 1

Views: 2474

Answers (1)

Matthew Green
Matthew Green

Reputation: 10401

When you use ngRoute, you are using javascript to handle routing to create a SPA. That means you need to hit a real page that loads your routing for your application to know what page to route to.

For example, your http://localhost:8080/appName/ should be routing to your index.html which would contain the javascript for your routing. With that page loaded it knows how to handle the links you have in your application. However, if you were to go directly to http://localhost:8080/appName/pageName you also need that to load index.html, as it is the one that loads your routing. Once your routing is loaded it should direct you to the correct page in your application. Without redirecting in place, http://localhost:8080/appName/pageName is not a real page and therefore correctly returns a 404.

Knowing this, the thing you have to figure out is what kind of server setup you have to configure the appropriate redirects for everything under http://localhost:8080/appName/ to go to your index.html page.

Upvotes: 3

Related Questions