When I post with AngularJS's HttpProvider
for an endpoint created with Django's standard View or Django REST framework, I get a 403 error. Come on.
$http.post('/api/entries', {'title': 'diary', 'body': 'It is a good weather today'})
Response
{detail: "CSRF Failed: CSRF token missing or incorrect."}
This is because I haven't been able to get around Django's CSRF Protection well, regardless of using AngularJS.
It seems that the value of Request Header that stores CSRF Token is different between the value used by AngularJS by default and the value recognized by Django.
If you read the following documentation, Django will have to send the value of csrftoken
with the header name X-CSRFToken
when making an Ajax request.
Cross Site Request Forgery protection | Django documentation | Django
AngularJS's HTTPProvider
has an option to change the behavior of CSRF Protection, and if you specify this, you can change the header name when sending the CSRF Token and the key of the cookie to be referenced.
[AngularJS: API:
To make settings for Django, set as follows.
var myApp = angular.module('myApp', []).config(function($httpProvider) {
$httpProvider.defaults.xsrfCookieName = 'csrftoken'
$httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken'
});
Now AngularJS will automatically interpret and send the csrftoken
without you having to do anything. Congratulations.
There's one more addiction to using AngularJS with Django, and AngularJS's variable expansion conflicts with Django's template engine, so you can't do variable expansion by default.
You can be happy if you change the symbol by referring to the following.
How to resolve variable scope conflicts between AngularJS and jinja2 --Qiita
Recommended Posts