在试图将django服务器连接到axios时,我遇到了问题。这应该是一个简单的修复,但我被卡住了!
我从django服务器得到了这个错误:
[23/Aug/2021 19:25:36] "POST /subscription HTTP/1.1" 403 2519
Forbidden (CSRF token missing or incorrect.): /subscription
下面是我使用的方法:
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;
}
我尝试过添加自定义标题,但我认为名称中的破折号引起了问题,我不知道如何解决它。
headers: { set-cookie: "csrftoken=ee95ec102d0d884ea95eb09cb421cdd8382aed79" }
我知道我的Django代码很好,因为它在浏览器中工作。我已附上它作为参考。
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")
以下是我在settings.py中的权限
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.AllowAny'
],
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.BasicAuthentication',
),
}
任何直升机都能救我的命!
发布于 2021-08-24 00:08:05
在django 文档中,给出了将csrf令牌设置为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) {
// ...
});
如您所见,csrf没有放在set-cookie
头中。它被放入一个名为X-CSRFToken
的头中。
发布于 2022-04-15 22:12:06
这很容易,但我花了几个小时才弄清楚。关键是指定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);
});
}
https://stackoverflow.com/questions/68900257
复制相似问题