代码之家  ›  专栏  ›  技术社区  ›  strumpy_strudel

试图在Axios GET的主体中发送数据以在Django后端中使用,但request.body的打印为空

  •  1
  • strumpy_strudel  · 技术社区  · 7 年前

    根据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)
    
    2 回复  |  直到 7 年前
        1
  •  1
  •   strumpy_strudel    7 年前

    与Keith Brewster一样,Axios使用XMLHttpRequest,它不支持在请求体中发送数据。一个解决方案是按照David Ryan的建议并补充 pos_title 添加到URL的一部分。不过,如果表中有空格,这会造成一些麻烦 职位名称 在我的案子里有。

    然而,在我的例子中,我决定在客户端进行过滤,因此保持原样,过滤响应就足以解决我的问题。

        2
  •  0
  •   David Ryan    7 年前

    推荐文章