使用Axios发送POST请求后Django后端接收空QueryDict的问题
解决Axios POST请求Django后端无法解析JSON数据的问题
问题场景
使用Axios发送POST注册请求,前端已构造包含firstname、username等字段的JSON数据,但Django后端通过request.POST获取到空QueryDict;解码request.body得到JSON字符串后,无法像字典一样取出username这类具体字段值,触发类型错误,需实现正常解析并获取请求字段。
相关代码
前端Axios代码
register: function (){ console.log("register start"); if (this.password !== this.confirmPassword) { alert("The Password IS DIFFERENT THAN CONFIRM PASSWORD!"); } else { console.log("register start"); const data = { firstname: this.firstname, lastname: this.lastname, username: this.username, email: this.email, password: this.password, confirmPassword: this.confirmPassword } console.log(data) axios.post("/register", data) .then(res => { alert("Register Success!"); console.log(res); }) .catch(error => { console.log(error); }) } }
后端初始接收代码
def register(request): try: # receive POST request, queryDict object if request.method == "POST": print("Post Request Received") user_info = request.POST print(request.body) print(user_info) except Exception as e: print("Error", e) return render(request, "error.html", context=e) return render(request, "register.html")
解码request.body的尝试代码
if request.method == "POST": print("Post Request Received") request_data = request.body user_info = request_data.decode("utf-8") print(user_info)
解决方案
问题原因
Axios默认发送的请求Content-Type为application/json,而Django的request.POST仅处理**表单编码(application/x-www-form-urlencoded)**的数据,因此无法获取JSON格式的请求体;解码request.body得到的是字符串类型,自然不能像字典一样直接取值。
正确解析方式
方式一:使用json模块解析请求体
导入Python内置的json模块,将解码后的JSON字符串转为字典:
import json def register(request): try: if request.method == "POST": print("Post Request Received") # 解析JSON字符串为字典 user_info = json.loads(request.body.decode("utf-8")) # 直接通过键名获取字段 username = user_info.get("username") firstname = user_info.get("firstname") print(username, firstname) except Exception as e: print("Error", e) return render(request, "error.html", context={"error": str(e)}) return render(request, "register.html")
方式二:使用Django内置的request.json(Django 3.1+)
Django 3.1及以上版本提供了request.json属性,可直接获取解析后的JSON字典:
def register(request): try: if request.method == "POST": print("Post Request Received") user_info = request.json username = user_info.get("username") print(username) except Exception as e: print("Error", e) return render(request, "error.html", context={"error": str(e)}) return render(request, "register.html")
额外说明
如果一定要让request.POST能获取数据,可修改Axios请求配置,将Content-Type设为application/x-www-form-urlencoded,并使用qs库序列化数据,但这种方式不如JSON格式符合前后端分离的主流实践,不推荐。
内容的提问来源于stack exchange,提问作者Winston
相关产品推荐
相关产品推荐

