简体   繁体   中英

Django and Axios Forbidden (CSRF token missing or incorrect.)

I am having issue with my django server when trying to connect it to axios. It should be a simple fix but I am stuck!

I am getting this error from my django server:

[23/Aug/2021 19:25:36] "POST /subscription HTTP/1.1" 403 2519
Forbidden (CSRF token missing or incorrect.): /subscription

Here is the method I am using:

const newsletterSignUp = async function (email) {
  try {
    let res = await axios({
      method: "post",
      url: "http://127.0.0.1:8000/subscription",
      data: { email: email },
    });

    return res;
  } catch (err) {
    console.error(err);
    return err;
  }

I have tried adding custom headers, but I think the dash in the name is causing issues and I don't know how to solve it.

headers: { set-cookie: "csrftoken=ee95ec102d0d884ea95eb09cb421cdd8382aed79" }

I know my Django code is fine since it works in the browser. I have attached it for reference.

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Email subscriptions</title>

    <!-- Bootstrap -->
    <link
      rel="stylesheet"
      href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css"
    />
  </head>

  <body class="container py-4">
    <!--Email subscription Form -->
    <form method="post" action="{% url 'subscription' %}">
      {% csrf_token %}

      <div class="form-group">
        <label>Subscribe to get the latest Articles</label> <br />
        <input
          type="email"
          name="email"
          placeholder="Enter Email to Subscribe"
        />
        <button class="btn btn-info" type="submit">Submit</button>
      </div>
    </form>

    <!-- message if email is sent -->
    {% if messages %} {% for message in messages %}
    <div class="my-5 alert alert-success">
      <h5 class="m-0">{{ message }}</h5>
    </div>
    {% endfor %} {% endif %}
  </body>
</html>

urls.py

urlpatterns = [
    path('', include(router.urls)),
     path("subscription", views.subscription, name="subscription"),
]

views.py

from django.shortcuts import render

# Create your views here.
from rest_framework import generics
from rest_framework import viewsets
from django.http import HttpResponse

from rest_framework.response import Response

from django.contrib import messages
from django.conf import settings
from mailchimp_marketing import Client
from mailchimp_marketing.api_client import ApiClientError

# Mailchimp Settings
api_key = settings.MAILCHIMP_API_KEY
server = settings.MAILCHIMP_DATA_CENTER
list_id = settings.MAILCHIMP_EMAIL_LIST_ID


# Subscription Logic
def subscribe(email):
    """
     Contains code handling the communication to the mailchimp api
     to create a contact/member in an audience/list.
    """

    mailchimp = Client()
    mailchimp.set_config({
        "api_key": api_key,
        "server": server,
    })

    member_info = {
        "email_address": email,
        "status": "subscribed",
    }

    try:
        response = mailchimp.lists.add_list_member(list_id, member_info)
        print("response: {}".format(response))
    except ApiClientError as error:
        print("An exception occurred: {}".format(error.text))

        # Views here.

def subscription(request):
    if request.method == "POST":
        email = request.POST['email']
        subscribe(email)                    # function to access mailchimp
        messages.success(request, "Email received. thank You! ") # message

    return render(request, "index.html")

Here are my permissions in settings.py

REST_FRAMEWORK = {

    'DEFAULT_PERMISSION_CLASSES': [
       'rest_framework.permissions.AllowAny'
    ],

    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.BasicAuthentication',
    ),
}

Any helo would save my life!

In the django docs , it gives this example for setting the csrf token on a request to django.

const request = new Request(
    /* URL */,
    {headers: {'X-CSRFToken': csrftoken}}
);
fetch(request, {
    method: 'POST',
    mode: 'same-origin'  // Do not send CSRF token to another domain.
}).then(function(response) {
    // ...
});

As you can see the csrf is not put in the set-cookie header. It is put in the in a header called X-CSRFToken .

It's super easy but took me hours to find out. Crucial is to specify the axios.defaults -

function post_email() {
  axios.defaults.xsrfCookieName = 'csrftoken'
  axios.defaults.xsrfHeaderName = "X-CSRFTOKEN"
  axios.post(
    '{% url 'email_subscribe' %}', {
      email: 'fred@gmail.com'
    })
    .then(function (response) {
      console.log(response);
    })
    .catch(function (error) {
      console.log(error);
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM