簡體   English   中英

Django的request.POST.get

[英]request.POST.get with django

方法一:不工作

def register(request):
    if request.method == "POST":
        username = request.POST.get("username")
        email    = request.POST.get("email")
        password = request.POST.get("password")
        print(username,email,password)

方法二:工作

def register(request):
    if request.method == "POST":
        data    = request.body
        convert = data.decode("utf-8")
        ds      = json.loads(convert)
        username = ds["username"]
        email    = ds["email"]
        password = ds["password"]
        print(username,email,password)

反應功能

  onSubmitSignUp = () => {
    fetch('http://127.0.0.1:8000/register/', {
      method:'post',
      headers:{'Content-Type':'application/json'},
      body:JSON.stringify({
        username:this.state.username,
        email:this.state.email,
        password:this.state.password

      })
    })
    .then(response => response.json())
    .then(user => {
      if(user){
        console.log(user);
      }else{
          console.log("error");
      }
    })
  }

當我通過post方法從frontend(react)發送數據時,它以第二種方式工作。

我想要第一個(Django標准)。

第一個也在郵遞員中工作,但不在瀏覽器中工作。

嘗試將內容類型設置為application/x-www-form-urlencoded

headers:{'Content-Type':'application/x-www-form-urlencoded'},

原因是您應該將formdata發送到django服務器。 如果確實要第一個,則應將反應代碼更改為此:

onSubmitSignUp = () => {
    let formData = new FormData();
    formData.append('username', this.state.username);
    formData.append('email', this.state.email);
    formData.append('password', this.state.password);

    fetch('http://127.0.0.1:8000/register/', {
            method: 'post',
            body: formData
        })
        .then(response => response.json())
        .then(user => {
            if (user) {
                console.log(user);
            } else {
                console.log("error");
            }
        })
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM