我使用 axios 发送 POST 请求,这是我的代码:
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);
})
}
}
这是接收 POST 请求的代码:
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")
但是,我一直收到一个空的 QueryDict,但我确实确认返回类型是 Json,它确实收到了一些东西,这是输出:
Post Request Received b'' QueryDict}
我找到了一个方法,就是复制POST请求并解码。这是代码:
if request.method == "POST":
print("Post Request Received")
request_data = request.body
user_info = request_data.decode("utf-8")
print(user_info)
这是更改后的输出:
Post Request Received
{"firstname":"First Name","lastname":"Last Name","username":"username123","email":"[email protected]","password":"12345678","confirmPassword":"12345678"}
[25/Mar/2023 16:07:07] "POST /register HTTP/1.1" 200 5347
Post Request Received
------WebKitFormBoundarycXOVuwbkiaqZTvQy--
[25/Mar/2023 16:07:07] "POST /register HTTP/1.1" 200 5347
问题是我无法修改或获取更具体的数据,例如“用户名”。我使用了
print(user_info["username"])
,但是,输出显示context must be a dict rather than TypeError.
我希望我可以像这样从 POST 请求中接收数据:
{"firstname":"First Name","lastname":"Last Name","username":"username123","email":"[email protected]","password":"12345678","confirmPassword":"12345678"}
并且能够从字典中取出特定的数据。例如可以打印出来print(user_info["username"])
如果您希望数据在 request.POST 中可用,您需要将数据作为
FormData
发送
let formData = new FormData();
formData.append('firstname', this.firstname);
...
axios.post("/register", formData)
.then(res => {
alert("Register Success!");
console.log(res);
})
.catch(error => {
console.log(error);
})
}
要修复您当前的做事方式,您需要解析 request.body:
import json
user_info = json.loads(request.body.decode('utf-8'))
print(user_info["username"])
此外,
render()
中的上下文应该始终是字典,因此显示错误的正确方法是:
...
except Exception as e:
print("Error", e)
return render(request, "error.html", context={"e": e})