Home > database >  Error 400 (Bad Request) when calling server using POST method in MERN
Error 400 (Bad Request) when calling server using POST method in MERN

Time:07-21

I created a delete user account button in my reactjs application. When this button is clicked, a form is displayed where the user must enter the password of the current account and then click Delete in order to delete the account. However, when I test this functionality, when I click on the Delete button, this does not delete the user account and in the command line I get the error:

POST http://localhost:5000/api/auth/delete_profile 400 (Bad Request)

Here is my file DeleteAccount.js:

<form onSubmit={handleDeleteUser}>
            ...
              <TextField
                error={error && error.password ? true : false}
                helperText={error && error.password ? error.password : null}
                onChange={handlePasswordChange}
                 ...
              />
             ...
          </form>

my useDeleteProfile.js file:

try {
      const { data } = await axios.post(`${url}/api/auth/delete_profile`,initialState)
              ...
        history.push('/')
}

my Auth.js file:

const DeleteAccount = require("../controllers/Auth/DeleteProfile")
  ...
router.post('/delete_profile',authRequired, DeleteAccount)

my DeleteProfile.js file :

module.exports = async (req, res) => {
  const { password } = req.body
  let error = {}

  if (!password || password.trim().length === 0) {
    error.password = 'password must be required'
  }

  
  if (Object.keys(error).length) {
    return res.status(422).json({ error })
  }

  try {

    const verifyPassword = await bcrypt.compare(password, user.password)
    if (!verifyPassword) {
      return res.status(400).json({ error: 'password is incorrect' })
    } else {

    await User.deleteMany({ user: req.userId })
    res.status(200).json({ message: 'User Deleted Successfully' })

    }
  } catch (err) {
    console.log(err)
    return res.status(500).json({error:"Something went wrong"})
  }

}

To resolve this error, I replaced the POST method with the DELETE method since it was a delete operation. Like this in my useDeleteProfile.js file:

 const { data } = await axios.delete(`${url}/api/auth/delete_profile`,initialState)

And like this in my Auth.js file :

router.delete('/delete_profile',authRequired, DeleteAccount)

now, I obtain the following error:

DELETE http://localhost:5000/api/auth/delete_profile 400 (Bad Request)

. So I modified my useDeleteProfile.js file like this, but nothing:

const { data } = await axios.delete(`${url}/api/auth/delete_profile`,
       initialState,
      {
        headers: {
          Authorization: `Bearer ${token}`,
        },
      },
    )

I also modified my Auth.js file like this :

router.delete('/api/auth/delete_profile',authRequired, DeleteAccount)

but now, I obtain the following error:

DELETE http://localhost:5000/api/auth/delete_profile 404 (Not Found)

I also looked on this stackoverflow question but without success. Someone can help me ? Thanks !

CodePudding user response:

You are getting an error because you are using an incorrect routing path.

Below is the correct way

For POST http://localhost:5000/api/auth/delete_profile use

router.post('/api/auth/delete_profile',authRequired, DeleteAccount)

For DELETE http://localhost:5000/api/auth/delete_profile use

router.delete('/api/auth/delete_profile',authRequired, DeleteAccount)

CodePudding user response:

Why you have added /api/auth/ prefix only put your relative path

router.delete('/api/auth/delete_profile',authRequired, DeleteAccount)

replace to

router.delete('/delete_profile',authRequired, DeleteAccount)

  • Related