axios 从POST请求接收后,QueryDict为空

vawmfj5a  于 2023-03-29  发布在  iOS
关注(0)|答案(2)|浏览(159)

我使用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"])

mnemlml8

mnemlml81#

如果你希望数据在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()中的上下文应该始终是一个dict,因此显示错误的正确方法是:

...
    except Exception as e:
        print("Error", e)
        return render(request, "error.html", context={"e": e})
2skhul33

2skhul332#

下面是我对这个问题的回答。在Vue.js的数据中,我删除了dataForm,并使用了data dict。

const data = {
                              firstname: this.firstname,
                              lastname: this.lastname,
                              username: this.username,
                              email: this.email,
                              password: this.password,
                              confirmPassword: this.confirmPassword
                          }

如果我使用正常的程序来接收POST请求,会有两个请求同时被接收。下面是POST请求的输出:

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

请求的类型为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类型。下面是我的整个过程的代码:

try:
        # receive POST request, queryDict object
        if request.method == "POST":
            # For filter WebKitFormBoundary POST request string
            if request.body.decode('utf-8')[0] == "{":
                response = request.body.decode('utf-8')  # response is a string
                response = json.loads(response)       # response is a json object(dict)
                print(response)

                first_name = response["firstname"]
                last_name = response["lastname"]
                user_name = response["username"]
                email = response["email"]
                password = response["password"]
                confirm_password = response["confirmPassword"]

                return render(request, "register.html")

    except Exception as e:
        print("Error", e)
        return render(request, "error.html", context={"error": e})

相关问题