javascript - 尝试在 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)
解决方案
正如 Keith Brewster 一样,Axios 使用 XMLHttpRequest,它不支持在请求正文中发送数据。一种解决方案是执行 David Ryan 的建议并添加pos_title
到 URL 的一部分。pos_title
如果在我的情况下有空格,这会让人头疼。
但是,就我而言,我决定在客户端进行过滤,因此保持原样并过滤响应足以解决我的问题。
推荐阅读
- tensorflow - 在模型定义中使用循环和 Lambda 层时发生 Keras load_model 错误
- android - 如何将 .docx 转换为 .txt 或从 android 中的 docx 文件中获取文本?
- javascript - canActive 角度如何从身份验证中获取值真假(用户登录与否)
- r - 按每个组中的子组汇总(&group by)
- configuration - 无法通过 LuCI 或 SSH 访问 OpenWrt
- javascript - 检查是否所有必填字段都填写在特定的 div 中
- java - spring mvc中不同的@ModelAttribute
- android - 如何将我的 XML 文件保存到特定文件夹?
- reactjs - 如何在 React Hooks 中使用 Antd 进行搜索
- amazon-web-services - Glue 是否需要安全配置才能从加密存储桶运行 Athena 查询?