Categories
Javascript Python

Django REST Framework & AngularJS $resource – Trailing Slash Problem

If you use ngResource ($resource) from AngularJS, you probably have already noticed that AngularJS removes the trailing slash from an URL. Django, on the other hand by default has “APPEND_SLASH” turned on. So when you request:

http://example.com/api/object

Django redirects you to:

http://example.com/api/object/

Yes, Django adds an extra slash to the URL. Django REST framework also follows this scheme. Every api end point has a trailing slash.

Angular, not having any trailing slash will always request the first URL above and get redirected to the second one. Apart from the cost of one extra http request, this is fine. The pain appears when we want to make POST request. Django can’t redirect POST requests and won’t accept POST data on the URL without a slash at the end. Damn, Our AngularJS app breaks because it can’t make request to the URL Django expects!

This is a very annoying and known bug with an open issue on their Github for quite sometimes. Since the latest version doesn’t yet have it fixed, I was stuck. Then I noticed somewhere that Django REST Framework responds to this particular bug allowing an extra parameter to “DefaultRouter” to create API endpoints without any trailing slash. Just do this –

api_router = routers.DefaultRouter(trailing_slash=False)

It will make sure that the API urls don’t have any slash at the end and play nice with Angular. But we’re not done yet, Django will still try to redirect requests appending a slash. Let’s fix this by adding this to the main settings.py:

APPEND_SLASH = False

Now, we should be able to make REST calls using AngularJS and $resource with sanity! 🙂

4 replies on “Django REST Framework & AngularJS $resource – Trailing Slash Problem”

Yes and no.

Angular by now has a setting to not remove the trailing slash:

myApp.config(function($resourceProvider){
$resourceProvider.defaults.stripTrailingSlashes = false;
});

But the actual default is to remove it, so you’ll have to set this option explicitly.

I prefer this method over Masnuns because I think that the basic functionality of the API provider should be modified as little as possible… Still, his method is entirely viable.

Comments are closed.