首页 > 解决方案 > 尝试在 Axios GET 的正文中发送数据以在 Django 后端使用,但 request.body 的打印为空

问题描述

根据 Axios,这应该是可能的:

https://github.com/axios/axios/issues/462#issuecomment-252075124

我有以下内容并且pos_title确实有价值。

export function getQuery(pos_code, id) {
    if (id === 94) {
        var strArray = pos_code.split(' - ');
        pos_code = strArray[0];
        var pos_title = strArray[1];
    }
    return function(dispatch) {
        axios.get(
            `${URL}/api/survey/${(id)}/results/${(pos_code)}/`,
            { 
                headers: { 
                    'Content-Type': 'application/json',
                    'Authorization': 'JWT ' +  sessionStorage.getItem('token')
                },
                data: {
                    body: pos_title
                }
            }
        )
        .then(response => {
            dispatch({
                type: QUERY,
                payload: response.data
            })
        })
        .catch(error => {
            console.log(error);
        }) 
    }
}

在相应views.py的 中,print(body_data)为空:

class GetQueryDataAPIView(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request, *args, **kwargs):
        data = {'id': request.user.id}
        if kwargs:
            data['survey_id'] = kwargs.get('survey_id')
            data['pos_code'] = kwargs.get('pos_code')
        if data['survey_id'] == 94:
            body_unicode = request.body.decode('utf-8')
            body_data = json.loads(body_unicode)
            print(body_data)
        serializer = GetQueryDataSerializer(data=data)
        if serializer.is_valid(raise_exception=True):
            return Response(serializer.data, status=HTTP_200_OK)
        return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)

标签: javascriptdjangoreactjsdjango-rest-frameworkaxios

解决方案


正如 Keith Brewster 一样,Axios 使用 XMLHttpRequest,它不支持在请求正文中发送数据。一种解决方案是执行 David Ryan 的建议并添加pos_title到 URL 的一部分。pos_title如果在我的情况下有空格,这会让人头疼。

但是,就我而言,我决定在客户端进行过滤,因此保持原样并过滤响应足以解决我的问题。


推荐阅读