I'm struggling to figure out how to console log an error I am getting from my django-rest framework. This is what I currently have
const onSubmit = (data) => {
const user = {
username: data.username,
email: data.email,
password: data.password,
profile: {
city: data.city,
country: data.country,
}
};
fetch('http://127.0.0.1:8000/api/register', {
method: 'POST',
headers: {
'Content-Type':'application/json'
},
body: JSON.stringify(user)
})
.then(res => res.json())
.then((data) => {
})
.catch((resp)=>{console.log(resp)})
};
This is an example of an error I am getting:
{"username":["A user with that username already exists."]}
This is a 400 Error
CodePudding user response:
this is your console.log()
==> {"username":["A user with that username already exists."]}
to catch your error
message from your server. If your goal is to test your application. Don't use the same username or clear the user from the database first.
CodePudding user response:
Figured out that the error message was in a promise so I had to resolve the promise to be able to console the error message:
const onSubmit = (data) => {
const user = {
username: data.username,
email: data.email,
password: data.password,
profile: {
city: data.city,
country: data.country,
}
};
fetch('http://127.0.0.1:8000/api/register', {
method: 'POST',
headers: {
'Content-Type':'application/json'
},
body: JSON.stringify(user)
})
.then(res => {
if(!res.ok){
return res.text().then(text=> {console.log(text) })
}
else {
return res.json().then(data=> {console.log(data) })
}}) }