0

I am using fetch to get data processed in back end now the transaction works fine. What im trying to achieve is I want to handle different senarios when they happen. What i mean by that is for example if the request is successful and server sends a response back with no errors I want to get that data sent from the server and get a specific value from the object sent back but if error happens when proccessing and server sends back lets say error code 400 with a custom data explaining about it I want to catch that error by its status code then get what the specific error was from the custom data by getting data.error in my case then log that error string. I have a rough sketch of this proccess bellow on my code with comments on what im tring to achive but there are some problems in it for example how do check if the response status code is 400. Right now I just used if (error.resposeStatus == 400). Can you please take a look at my code and help me fix the flaws. Thanks in advance

$('.sign_upBtn').on('click', async function() {
  const name = $('.nameCon input').val()
  const username = $('usernameCon input').val()
  const password = $('.passwordCon input').val()
  await fetch('/api/user/register', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        "name": name,
        "username": username,
        "password": password
      })
    })
    .then((res) => res.json())
    //if there is no error
    .then(data =>
      if (data.name == 'john') {
        console.log(data)
      }
    )

    //if there is error
    .catch(error => {
      //somthing like this (this is rough sketch)
      if (error.responseStatus == 400) {
        //get the res data send from server (I used data.error because im getting my res from server like this: {error: 'this is the error')
        data =>
          if (data.error == 'username already exists') {
            //dom manipulation blah blah
            console.log('user name is in use')
          }
      }
    })
})
router.post('/register', async(req, res) => {
  //check if user is already in database
  const usernameExist = await User.findOne({
    username: req.body.username
  })
  if (usernameExist) return res.status(400).send({
    error: 'username already exists'
  })

  //create new user
  const user = new User({
    name: req.body.name,
    phone_number: req.body.phone_number,
    username: req.body.username,
    password: req.body.password
  })
  try {
    const savedUser = await user.save()
    res.send(savedUser)
  } catch (err) {
    res.send(400).send(err)
  }
})
Phil
  • 157,677
  • 23
  • 242
  • 245
seriously
  • 1,202
  • 5
  • 23
  • Fetch is a bit weird because a failed request is still counted as completing correctly. In your `then` block, you should check the status code with `res.ok && res.status === 200` to confirm it completed successfully. – alex87 Jun 21 '22 at 02:15
  • @Phil not really because after I get the status code I also want to check what the res sent was then based on that error data apply the required dom manipulation (in this case just log error value) – seriously Jun 21 '22 at 02:17
  • Yep, so use `if (res.status === 400) { const errData = await res.json(); ...` – Phil Jun 21 '22 at 02:20
  • FYI I'd use `res.status(500).send(err)` for that last one if the DB save fails – Phil Jun 21 '22 at 03:04

0 Answers0