首页 > 解决方案 > Axios put 请求无法与 Django Rest Framework 一起正常工作

问题描述

从 axios 我必须向 DRF 提出 put 请求。在 DRF 中,我使用 APIView 基于类的视图。在我发出 put 请求时收到 403 禁止错误之前。因为它没有在请求中发送 csrftoken。我用谷歌搜索了它并使用 Django 浏览了 CSRF,使用 Axios堆栈溢出问题的 React+Redux 并且不知何故我能够修复 403 禁止问题。

通过上面的 StackOverflow 问题,我更改了几行代码,它们就是。

在我的 axios 文件中

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

在我的项目设置中。.py 文件

ALLOWED_HOSTS = ['*']

CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True

但是,当我将任何数据传递给来自 axios 的彻底 put 请求时,wiered 部分就在这里,它实际上从那里将流传递给 APIView 类(这是我的假设),我得到了一个有线响应。我可以看到它将反应的 index.html 作为响应中的数据发送。

我的views.py代码

class TestView(APIView):
    def put(self, request):
        print('inside put method')
        print(request.data)
        return Response('Test data passing in return')

我的 Axios 代码

import axios from "axios";
axios.defaults.xsrfHeaderName = "X-CSRFToken";
axios.defaults.xsrfCookieName = "csrftoken";
axios.defaults.withCredentials = true;

return axios({
        method: "put",
        url: API_URL,
        data: alterRecord
    })
        .then(res => {
            console.log("inside then");
            console.log(res);
        })
        .catch(e => {
            console.log("Inside catch");
            console.log(e.message);
        });

在用于测试目的的 APIView 类中,我添加了打印语句,它不会在命令行中打印这些行。当我在命令行中看到请求时,我看到 OPTIONS 方法也被调用了,我不知道为什么。

[09/Oct/2019 18:02:09] "OPTIONS /api/url/ HTTP/1.1" 200 0
[09/Oct/2019 18:02:09] "PUT /api/url/ HTTP/1.1" 200 2102

在 axios 响应数据中,我可以看到它正在像这样传递 react 的 index.html 数据

data: "<!doctype html><html lang="en"><head><meta charset="utf-8"/><link rel="shortcut icon" href="/favicon.ico"/><meta name="viewport" content="width=device-width,initial-scale=1"/><meta name="theme-color" content="#000000"/><link rel="manifest" href="/manifest.json"/><title>NoA</title><link href="/static/css/2.39680177.chunk.css" rel="stylesheet"><link href="/static/css/main.87078788.chunk.css" rel="stylesheet"></head><body><noscript>You need to enable JavaScript to run this app.</noscript><div id="root"></div><script>!function(l){function e(e){for(var r,t,n=e[0],o=e[1],u=e[2],f=0,i=[];f<n.length;f++)t=n[f],p[t]&&i.push(p[t][0]),p[t]=0;for(r in o)Object.prototype.hasOwnProperty.call(o,r)&&(l[r]=o[r]);for(s&&s(e);i.length;)i.shift()();return c.push.apply(c,u||[]),a()}function a(){for(var e,r=0;r<c.length;r++){for(var t=c[r],n=!0,o=1;o<t.length;o++){var u=t[o];0!==p[u]&&(n=!1)}n&&(c.splice(r--,1),e=f(f.s=t[0]))}return e}var t={},p={1:0},c=[];function f(e){if(t[e])return t[e].exports;var r=t[e]={i:e,l:!1,exports:{}};return l[e].call(r.exports,r,r.exports,f),r.l=!0,r.exports}f.m=l,f.c=t,f.d=function(e,r,t){f.o(e,r)||Object.defineProperty(e,r,{enumerable:!0,get:t})},f.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},f.t=function(r,e){if(1&e&&(r=f(r)),8&e)return r;if(4&e&&"object"==typeof r&&r&&r.__esModule)return r;var t=Object.create(null);if(f.r(t),Object.defineProperty(t,"default",{enumerable:!0,value:r}),2&e&&"string"!=typeof r)for(var n in r)f.d(t,n,function(e){return r[e]}.bind(null,n));return t},f.n=function(e){var r=e&&e.__esModule?function(){return e.default}:function(){return e};return f.d(r,"a",r),r},f.o=function(e,r){return Object.prototype.hasOwnProperty.call(e,r)},f.p="/";var r=window.webpackJsonp=window.webpackJsonp||[],n=r.push.bind(r);r.push=e,r=r.slice();for(var o=0;o<r.length;o++)e(r[o]);var s=n;a()}([])</script><script src="/static/js/2.46fe2ccd.chunk.js"></script><script src="/static/js/main.c9f4f998.chunk.js"></script></body></html>"

在这里,我不确定为什么没有打印打印语句,为什么在这里调用 OPTION HTTP 方法,以及为什么我将 react 的 index.html 作为响应而不是 Response('Test data passing in return')。

如果我从邮递员那里发出相同的请求,它实际上会正确地发回响应。但是对于 axios,它不会。我确定我必须对 axios 做点什么。请问,谁能帮我解决这个问题?

标签: djangoreactjsdjango-rest-frameworkaxios

解决方案


推荐阅读