我使用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":"username123@gmail.com","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
问题是,我不能修改或从其中获取更具体的数据,例如“用户名”。
我希望我可以像这样从POST请求中接收数据:{"firstname":"First Name","lastname":"Last Name","username":"username123","email":"username123@gmail.com","password":"12345678","confirmPassword":"12345678"}
并且可以从dict中取出特定的数据。例如可以打印出print(user_info["username"])
2条答案
按热度按时间mnemlml81#
如果你希望数据在request.POST中可用,你需要将数据作为
FormData
发送要修复当前的处理方式,需要解析request.body:
此外,
render()
中的上下文应该始终是一个dict,因此显示错误的正确方法是:2skhul332#
下面是我对这个问题的回答。在Vue.js的数据中,我删除了dataForm,并使用了data dict。
如果我使用正常的程序来接收POST请求,会有两个请求同时被接收。下面是POST请求的输出:
请求的类型为String!因此,我们需要将String转换为Json类型(使用Json.loads)。但是,
Error: Expecting value: line 1 column 1 (char 0)
将被打印出来。这个错误意味着由于Post Request的第二部分不是正确的json类型(dict),它是普通的String(“------WebKitFormBoundary”),无法解析为Json类型。为了解决这个问题,我使用if语句来过滤POST请求的第二部分,下面是我的代码:if request.body.decode('utf-8')[0] == "{":
。现在,代码可以成功转换为JSON类型。下面是我的整个过程的代码: