Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JS fetch print details of bad request response

I am trying to use Django-rest-auth, I am getting it to work but often I get Bad request HTTP 400. In Django-rest-auth generated view I can see the details of the error (i.e username contains unaccepted chars or pwd do not match).

How can I get this information on frontend js side ? For now I was trying to just console the whole response but cannot find it in there

    const registerUser = async (user ) => {
      console.log( JSON.stringify(user))
      const response = await fetch("/api/dj-rest-auth/registration/", {
        method: "POST",
        headers: {
          "Content-Type": "application/json"
        },
        body: JSON.stringify(user)
      });

      if (response.status === 201) {
        console.log('did it ! !!! !! !!! ! !! ')
        let data = response.json()
        localStorage.clear();
        localStorage.setItem('authToken', data.key);

      } else {
        console.log(response);
      }
    };
    

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use try...catch as stated in comments by Konrad Linkowski.

const registerUser = async (user ) => {
      console.log( JSON.stringify(user))
   try {
      const response = await fetch("/api/dj-rest-auth/registration/", {
        method: "POST",
        headers: {
          "Content-Type": "application/json"
        },
        body: JSON.stringify(user)
      });

      if (response.status === 201) {
        console.log('did it ! !!! !! !!! ! !! ')
        let data = response.json()
        localStorage.clear();
        localStorage.setItem('authToken', data.key);

      } else {
        console.log(response);
      }
}catch (e){
console.log(e) // log the error , its an object so you can get desired error message
}
    };
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading