简体   繁体   English

Django 和 Axios 禁止访问(CSRF 令牌丢失或不正确。)

[英]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!我的 django 服务器在尝试连接到 axios 时出现问题。这应该是一个简单的修复,但我被卡住了!

I am getting this error from my django server:我从我的 django 服务器收到此错误:

[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.我知道我的 Django 代码没问题,因为它可以在浏览器中运行。 I have attached it for reference.我附上它以供参考。

index.html 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网址.py

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

views.py视图.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这是我在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.在 django 文档中,它给出了这个示例,用于在对 django 的请求中设置 csrf 令牌。

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 .如您所见,csrf没有放在set-cookie header 中。它放在名为X-CSRFToken中。

It's super easy but took me hours to find out.这非常简单,但我花了好几个小时才弄明白。 Crucial is to specify the axios.defaults -关键是指定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);
    });
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在 Django 中的 ajax POST 期间禁止(CSRF 令牌丢失或不正确。) - Forbidden (CSRF token missing or incorrect.) during ajax POST in Django “禁止(CSRF 令牌丢失或不正确。):”使用 Django 和 JS - “Forbidden (CSRF token missing or incorrect.):” using Django and JS 禁止(CSRF 令牌丢失或不正确。) | Django 和 AJAX - Forbidden (CSRF token missing or incorrect.) | Django and AJAX 尽管正确发送令牌,Django 服务器仍报告“禁止(CSRF 令牌丢失或不正确。)”? - Django server reporting "Forbidden (CSRF token missing or incorrect.)" despite sending token correctly? 错误:使用 django rest 框架时禁止(CSRF 令牌丢失或不正确。) - Error :Forbidden (CSRF token missing or incorrect.) while using django rest framework 禁止(CSRF令牌丢失或不正确。)Django如何解决?用我的代码 - Forbidden (CSRF token missing or incorrect.) Django how to solve?WITH MY CODE 禁止(CSRF令牌丢失或不正确。)-即使已包含 - Forbidden (CSRF token missing or incorrect.) - even though it's included 如何更正 django 中的以下代码,它给出错误“禁止(CSRF 令牌丢失或不正确。)” - How do I correct the following code in django, It's give an error “Forbidden (CSRF token missing or incorrect.)” 用yui设置Django CSRF_TOKEN,但控制台显示“ django.request禁止(CSRF令牌丢失或不正确。)”。 - Set Django CSRF_TOKEN with yui, but console says 'django.request Forbidden (CSRF token missing or incorrect.)' (缺少CSRF令牌或不正确。)在Django中使用AJAX - (CSRF token missing or incorrect.) using AJAX in Django
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM