How do I throw a real 404 or 301 with an Angular pushstate URL - angularjs

I'm using $routeProvider and $locationProvider to handle pushstate URLS in a single page app (SPA), something like this:
angular.module('pets', [])
.config(function($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider.when('/pet/:petId', {
controller: 'petController'
});
})
.controller('petController', function($scope, petService, $routeParams){
petService.get('/api/pets/' + $routeParams.petId).success(function(data) {
$scope.pet = data;
});
});
The URL is used to pull content from the server which may or may not exist.
If this was an ordinary multipage website, a request for missing content would trigger a 404 header response from the server, and a request for moved content would trigger a 301. This would alert Google to the missing or moved content.
Say for example I hit a URL like this:
http://example.com/pet/123456
and say there is no such pet in the database, how can my SPA return a 404 on that content.
Failing this, is there some other way to correctly alert the user or search engine that the requested URL doesn't exist? Is there some other solution I'm not considering?

The real question is does http://example.com/pet/123456 return anything at all?
If your starting point is http://example.com/ and there's a link to http://example.com/pet/123456 then Angular will call the petController which in turn makes an AJAX call to http://example.com/api/pet/123456.
A crawler wouldn't do that but instead would try to call http://example.com/pet/123456 directly.
So your server must be able to handle that call. If there is no pet with the id 123456 then it should return 404. Problem solved. If there is then it should return the SPA. The application should then handle the situation accordingly.

According to this answer How do search engines deal with AngularJS applications?, You should use Headless Browser to process crawlers requests, and serve back snapshots of the page with the appropriate Response Code. https://developers.google.com/webmasters/ajax-crawling/docs/html-snapshot
The google example did not include 301,302 or 404 cases. However, their code could be modified to analyze the content of the snapshot and change the response code.
I found prerender.io offers this service, but it is not free. However, they have a free plan if you have fewer than 250 pages. Prerender asks that in case of 404 or 301, you add a meta tag to the DOM.
<meta name="prerender-status-code" content="404">
this meta tag is then detected by their headless browser and the response code is changed.

Try this
angular.module('pets', [])
.config(function($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider.when('/pet/:petId', {
controller: 'petController'
}). otherwise({ yourUrl:'/404.html'}) // Render 404 view;
})

Related

firebase 404 page configuration in angularjs

I try to add a 404 page into my angularjs project which is hosted on firebase servers. I created a custom 404 page and added following code:
function routeConfig($stateProvider, $urlRouterProvider, $locationProvider)
{
$urlRouterProvider.otherwise('/pages/errors/error-404');
}
Now it works but I am missing something because when I check in the browser's network panel the status code is "200" but it should be "404".
What should I do for that?
$urlRouterProvider.otherwise just guides AngularJS that which URL it should navigate to when no URL matches the provider's rules.
This doesn't signify that a resource is not found on the server (which essentially returns 404). To do that, you need to do a lot more including serving this 404 page from the server with 404 as the status code.
Here is a resource to point you in the right direction:
AngularJS UI router handling 404s

How to make the angularJS pretty URL work directly in the browser? [duplicate]

Before removing the hash sign, I had
mainApp.config(function ($locationProvider, $routeProvider) {
$routeProvider
.when('/page', {
controller: 'Page',
templateUrl: 'templates/page.html'
})
.when('/main', {
controller: 'Main',
templateUrl: 'templates/main.html'
})
.otherwise({ redirectTo: '/main'});
//$locationProvider.html5Mode(true);
});
and these worked fine
http://localhost:8080/index.html#/main
http://localhost:8080/index.html#/page
After removing the pound sign, I added to index.html
<base href="/">
<script src="/vendor/bootstrap-dist/js/bootstrap.min.js"></script>
<script src="/vendor/javascript/angular/angular.js"></script>
<script src="/vendor/javascript/angular/angular-route.js"></script>
<script src="/vendor/javascript/angular/ui-bootstrap-tpls-0.11.2.min.js"></script>
<script src="/javascript/index.js"></script>
<script src="/javascript/controllers/main.js"></script>
<script src="/javascript/controllers/page.js"></script>
and to index.js
$locationProvider.html5Mode(true);
now hitting http://localhost:8080 redirects to http://localhost:8080/main
but going to http://localhost:8080/main directly in the browser returns 404 and the other pages too
What should I do to fix the problem?
my backend is java
That's expected. Here's what happens when html5 is not turned on:
you enter the url http://localhost:8080/index.html#/main in the address bar
the browser makes a http request to localhost:8080/index.html and gets the html page as a response
the html page contains an angular application that is executed. The angular router parses the path after the hash (/main), and thus loads the associated view and controller
Now what happens when you enable html5 mode and load index.hml?
you enter the url http://localhost:8080/index.html in the address bar
the browser makes a http request to localhost:8080/index.html and gets the html page as a response
the html page contains an angular application that is executed. The angular router parses the path (/index.html), sees that it doesn't match any route, and thus changes the location in the address bar to the default: /main, and then loads the associated view and controller. Changing the location in the address bar doesn't make the browser do anything other than adding a new entry in its navigation history.
Now, what happens if you hit refresh, or directly enter http://localhost:8080/main in the address bar? Well in that case, you're saying the browser: "please load the page at the url http://localhost:8080/main. So that's what the browser does: it sends an HTTP request to http://localhost:8080/main. Since the server doesn't have anything at this address, it sends back a 404.
Now how to make it work? It's actually quite simple: you need to configure the server to send back the index.html page when it gets a request for the path /main (and for all the other paths of the angular application). That way, the browser will load the HTML page, the angular application it contains will be restarted, the angular router will parse the path (/main) from the URL, and it will thus load the view and the controller associated to that path.

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.
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.

AngularJS and PhoneGap: $location.path causes subsequent tempateUrl lookup to fail

I'm having trouble getting path lookup to work with a AngularJS v1.2.0 and PhoneGap/Cordova Android application. I've come pretty far with html5mode(true) by setting <base href="."/> in index.html and then changing $routeProvider.when('/') to $routeProvider.when('/android_asset/www/index.html'). After that I am able to get redirectTo('login') to reach $routeProvider.when('/login') and there render templateUrl: 'static/partials/login.html' as expected.
The problem I have is that if I instead try to redirect to the login page from my Javascript code with $location.path('/login');, the route is found but templateUrl loading fails with an insecurl exception.
I've tried whitelisting access to file:// by using the new angular-sanitize module, but that does not help.
How can I make $location.path() do the same things as redirectTo so that the partial is loaded? Or is there some other way to solve this problem?
UPDATE: I got a bit forward by adding a call to replace() after the path function, e.g.:
$location.path('/login').replace();
but that seems like a hack, and it still causes the templateUrl in the otherwise route to fail with the same exception.
Any ideas on what might be wrong? Is it that html5mode(true) just does not work at this moment with Phonegap and the only way to fix this is to set it to false and add hashtags to every path (like is done in the angular phonegap seed project)?
For future reference, this is how I managed to solve the problem:
AngularJS currently does not seem to support html5mode(true) inside a Cordova application because of the insecurl problem I reported. What I had to do is add
var h5m = (typeof html5Mode !== 'undefined') ? html5Mode : true;
$locationProvider.html5Mode(h5m);
which gives me the possibility to explicitly set html5Mode in the PhoneGap index.html with a global variable:
<script>
var html5Mode = false;
</script>
So now $location.path('/login') as well as redirectTo: 'login' works, but links in html files, don't. To get those working in PhoneGap, with html5Mode disabled, I had to add #/ in front of every link, e.g. login.
That makes PhoneGap work, but breaks the web page which uses History API with html5Mode(true). The last piece of the puzzle was to add <base href="/"/> to the web page's index.html (and leave it out of the index.html of the PhoneGap project.) So now even though I have a link that says #/login in the web page, I get to the url http://example.com/login and don't see any hashes in the address bar.
**
So in the end I have History API working in my web page and History API disabled in the PhoneGap project (where there really is no need for History API as there is no address bar). The only downside is the extra #/ I have to put in each template html file, but that is a minor annoyance compared to the ability to use all of the same html and javascript files for both web and mobile.
I had this same problem as well. I managed to fix it by skipping the leading slash in the route config:
$routeProvider
// route for the foo page
.when('/foo', {
templateUrl: 'foo.html', //previously: '/foo.html'
controller: 'fooController'
}) //etc.

AngularJS routing with Mongoose webserver

I'm testing a website locally on my machine. It uses AngularJS for routing and page changes, and I'm attempting to test the routes using the Mongoose webserver (extremely light).
My code is as follows:
app.config(['$locationProvider', '$routeProvider', function ($locationProvider, $routeProvider) {
$locationProvider.html5Mode(true);
$routeProvider.when('/who', {templateUrl: '/js/partials/who', controller: 'whoPage'});
$routeProvider.when('/what', {templateUrl: 'partials/what'});
$routeProvider.when('/want', {templateUrl: 'partials/want'});
$routeProvider.otherwise({ redirectTo: '/' });
}]);
(I haven't set up controllers for some of the other pages yet. I've been testing the "who" page.)
I'm running the page from localhost:8080. In my application, when I click a link to change the location, nothing happens. The URL changes to "localhost:8080/who", but I get no messages from console, and I get no changes on my page. However, if I then refresh that URL, I get a 404 error.
I don't have any server-side routing set up. Is this a necessity for Angular apps? Is there something wrong with the code I've written, or should I try a different test webserver?
$locationProvider.html5Mode(true);
will make angular use "push state" from the HTML5 History API.
This means that you'll see the url change in the location bar, but that won't cause the browser to actually reload your page. When you reload the page, the browser will now fetch that url from the webserver, which doesn't have it.
A common trick is to use URL rewrites to map any url back to index.html. You should take care of not remapping the urls that point to static files such as your javascript and css resources. That's usually easy because it's a good practice to group all your css and js files in some directory instead of scattering them in the top level dir.
You can read about how to configure mongoose URL rewrites at https://www.cesanta.com/developer/binary#_url_rewrites

Resources