加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

Django React Axios

发布时间:2020-12-20 11:03:16 所属栏目:Python 来源:网络整理
导读:我正在尝试使用React和Axios向Django服务器发出一个发布请求.但是,我在服务器端获得了重定向302. 刚刚按照这篇文章中的所有建议CSRF with Django,React+Redux using Axios 不成功 :( 但是,到目前为止我所做的是以下内容: 坐在默认的axios CookieName和Head
我正在尝试使用React和Axios向Django服务器发出一个发布请求.但是,我在服务器端获得了重定向302.

刚刚按照这篇文章中的所有建议CSRF with Django,React+Redux using Axios
不成功 :(

但是,到目前为止我所做的是以下内容:
坐在默认的axios CookieName和HeaderName(在javascript端):

axios.defaults.xsrfHeaderName = "X-CSRFToken";
axios.defaults.xsrfCookieName = "XCSRF-Token";

在settings.py中也有这个:

CSRF_COOKIE_NAME = "XCSRF-Token"

以下是帖子请求的样子:

axios(
    {
        method: 'post',url: `/api/${selectedEntryType}_entry`,data: {
            "test": "test"
        },headers: {
            'X-CSRFToken': document.cookie.split('=')[1],'X-Requested-With': 'XMLHttpRequest','Content-Type': 'application/json',}
    }
)

我尝试的另一件事是从Django rest api UI发出post请求:

Django rest api UI

它确实成功.

当我从UI和JS发出请求时,请求标头中的唯一区别是:
接受,内容长度和引用,我不知道它们怎么会有问题.

请帮忙.

解决方法

管理通过更改我发布到的url(url:’/ en / api / endpoint /’)修复它,因为显然是为了POST请求:

You called this URL via POST,but the URL doesn’t end in a slash and you have APPEND_SLASH set. Django can’t redirect to the slash URL while maintaining POST data. Change your form to point to 127.0.0.1:8000/en/api/endpoint/ (note the trailing slash),or set APPEND_SLASH=False in your Django settings

之后我开始获得Forbidden 403,但是添加:

from django.views.decorators.csrf import csrf_protect
from django.utils.decorators import method_decorator

@method_decorator(csrf_protect)
def post(self,request):
    return Response()

并且还将JS中的默认值更改为:

axios.defaults.xsrfHeaderName = "X-CSRFToken";
axios.defaults.xsrfCookieName = "csrftoken";

并从settings.py中删除了CSRF_COOKIE_NAME =“XCSRF-Token”.

有效.

希望这有助于将来的某些人.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读