簡體   English   中英

在 MERN 中使用 POST 方法調用服務器時出現錯誤 400(錯誤請求)

[英]Error 400 (Bad Request) when calling server using POST method in MERN

我在我的 reactjs 應用程序中創建了一個刪除用戶帳戶按鈕。 單擊此按鈕時,將顯示一個表單,用戶必須在其中輸入當前帳戶的密碼,然后單擊刪除才能刪除該帳戶。 但是,當我測試此功能時,當我單擊“刪除”按鈕時,這不會刪除用戶帳戶,並且在命令行中出現錯誤:

POST http://localhost:5000/api/auth/delete_profile 400(錯誤請求)

這是我的文件DeleteAccount.js

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

我的useDeleteProfile.js文件:

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

我的Auth.js文件:

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

我的DeleteProfile.js文件:

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"})
  }

}

為了解決這個錯誤,我用DELETE方法替換了POST方法,因為它是一個刪除操作。 在我的useDeleteProfile.js文件中是這樣的:

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

在我的Auth.js文件中就像這樣:

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

現在,我收到以下錯誤:

刪除 http://localhost:5000/api/auth/delete_profile 400(錯誤請求)

. 所以我像這樣修改了我的useDeleteProfile.js文件,但沒有:

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

我還像這樣修改了我的 Auth.js 文件:

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

但現在,我收到以下錯誤:

刪除 http://localhost:5000/api/auth/delete_profile 404(未找到)

我也查看了這個stackoverflow 問題,但沒有成功。 有人可以幫助我嗎? 謝謝 !

您收到錯誤是因為您使用了不正確的路由路徑。

下面是正確的方法

對於POST http://localhost:5000/api/auth/delete_profile使用

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

對於DELETE http://localhost:5000/api/auth/delete_profile使用

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

為什么你添加 /api/auth/ 前綴只放你的相對路徑

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

替換為

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM