我在 Django 中使用 React,大多数客户端服务器交互都是通过使用 Django Rest Framework 的 API 完成的。我创建了一个名为 的标准应用程序mail
,它有一个标准视图,可以接受带有装饰器的POST
请求。但是,每当通过它拨打电话时,总是会给我一个csrf_exempt
login_required
ajax
Axios
403 Invalid CSRF Token error - CSRF Cookie not specified.
视图.py
from django.contrib.auth.decorators import login_required
from django.views.decorators.csrf import csrf_exempt
@login_required
@csrf_exempt
def testmail(request):
if request.method=="POST":
EmailQueue.objects.create(subject='TEST EMAIL BROTHER', body=render_to_string('nordalmail/testmail.html'), to_email=request.user.email, from_email=settings.FROM_EMAIL, send_now=True)
return HttpResponse("CHECK ADMIN")
if request.method == "GET":
return render(request, "nordalmail/test-mail.html")
反应组件
import axios from 'axios';
import {createMessage, returnErrors} from './messages.js';
import {tokenConfig} from './auth.js';
// Tokenconfig simply gets the Authorization Token and sends it as a Header value
export const sendTestMail = () => (loggedUserEmail, getState) => {
axios
.post('http://alice:55403/nordalmail/', tokenConfig(getState))
.then(res => {
createMessage("A test email has been sent to your registered email address!",
"Email Sent");
})
.catch(err => {
returnErrors("Something went wrong while sending your email, website administrator has been notified of this incidence!", "Error");
});
}
这是我发送的请求
Request URL: http://alice:55403/nordalmail/
Request Method: POST
Status Code: 403 Forbidden
Remote Address: 127.0.0.1:55403
Referrer Policy: no-referrer-when-downgrade
headers: {"headers":{"Content-Type":"application/json","Authorization":"Token 35a7aa30b26ebb1c269c6cca0cd323c07e028171aa268b61d0dfc41871f93de6"}}
我正在使用brave browser
,所以我真的不知道如何获得raw headers
. 我可以保证它的有效性,Authorization Token
因为它确实适用于其他适当的 API 端点。