javascript - Why do I get a 'CSRF token missing or incorrect' error? -


i trying return value view function in django. function being called javsscript code using ajax, thrown error reads 'forbidden (csrf token missing or incorrect)'.

javascript/ajax

the error message

the html code looks this:

    <div align="center" class="input-line">      <form class="input-form" method="post">{% csrf_token %}         <input type = "text" id = "ans" class = "form-control" name = "address" placeholder="type postcode..."><br><br>         <button id = "homebtn" class="btn btn-primary">find info</button><br><br>      </form> </div> 

the view function is:

    def result(request):         if(request == 'post'):            param = request.form['my data']            = runareareview(param) #this returns string            return httpresponse(this) 

method 1

for making post requests ajax, need set header called http_x_csrftoken , set it's value cookie stored in browser name csrftoken. reference. in ajax call, should this.

var csrftoken = cookies.get('csrftoken');  $.ajax(      ...      headers:{"http_x_csrf_token":csrftoken}  ); 

also note if using reverse proxy server nginx, make sure froward header django application.

method 2

you can disable csrf verification specific view using annotation. reference

from django.views.decorators.csrf import csrf_exempt  @csrf_exempt def result(request):     ... 

method 3

the method below not recommended security reasons

you can alwaws turnoff csrf middleware in settings rid of if building recreational purpose , not production.


Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

thorough guide for profiling racket code -