Way one: not working
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)
Way two: working
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)
react function
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");
}
})
}
When I send data from frontend(react) via post method it is working in the second way.
I want the first one (django standard).
The first one is working in postman also but not in browser.
尝试将内容类型设置为application/x-www-form-urlencoded
headers:{'Content-Type':'application/x-www-form-urlencoded'},
The reason is you should send formdata to django server. If you do want the first one,you should change the react code to this:
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");
}
})
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.