在Django REST + React框架中无法做axios PUT请求 - 错误403

时间:2018-02-26 05:49:40

标签: django reactjs django-rest-framework axios

我可以通过以下方式进行GET请求:

axios.get('/by/f')
        .then(function (data) {
            this.setState({list: data.data});
        }.bind(this))
        .catch(function (error) {
            console.log(error);
        });

然而,当我尝试更新我的django数据库的PUT请求时,我收到403错误:

axios({
        method: 'put',
        url: '/by/f',
        data: {
            item: item,
            frequency: frequency
        }
    }).then(function (response) {
        console.log(response);
    });

我的观点:

class FrequencyList(APIView):
def get(self, request, format=None):
    frequency = Frequency.objects.all()
    serializer = FrequencySerializer(frequency, many=True)
    return Response(serializer.data)

def put(self, request, pk, format=None):
    frequency = self.get_object(pk)
    serializer = FrequencySerializer(frequency, data=request.data)
    if serializer.is_valid():
        serializer.save()
        return Response(serializer.data)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

我的网址格式:

urlpatterns = [
    path('f', views.FrequencyList.as_view()),
]

我的标题:

headers: {
  'Access-Control-Allow-Origin': '*'
},

1 个答案:

答案 0 :(得分:1)

您的FrequencyList视图适用于获取所有频率列表和添加新频率。换句话说,对于FrequencyList视图,get和post请求都很好。但是您无法使用相同的视图来获取详细信息api(update / delete / getDeatails)。对于这些操作孩子,你需要频率的id。所以对于更新(put函数)创建新的api / view。

url.py

urlpatterns = [
    path('f', views.FrequencyList.as_view()),
    path('f/(?P<pk>[0-9]+)$', views.FrequencyDetail.as_view()),

views.py

class FrequencyList(APIView):
    def get(self, request, format=None):
        frequency = Frequency.objects.all()
        serializer = FrequencySerializer(frequency, many=True)
        return Response(serializer.data)

class FrequencyDetail(APIView)
    def put(self, request, pk, format=None):
        frequency = Frequency.objects.get(id=pk)
        serializer = FrequencySerializer(frequency, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

你的脚本应该是

axios({
        method: 'put',
        url: '/by/f/' + frequency, # hope frequency is the id of the object that you want to update
        data: {
            item: item,
        }
    }).then(function (response) {
        console.log(response);
    });

获取

没有变化
axios.get('/by/f')
        .then(function (data) {
            this.setState({list: data.data});
        }.bind(this))
        .catch(function (error) {
            console.log(error);
        });

<强>更新

如果要处理未找到对象错误

,则可以使用以下代码替换

frequency = Frequency.objects.get(id=pk)

queryset = Frequency.objects.all()
frequency = get_object_or_404(queryset, pk=pk) # from django.shortcuts import get_object_or_404