簡體   English   中英

使用 Axios ZCCADCDEDB567ABAE643E15DCF0974E503Z 更新無法正常工作

[英]Put Not Working to Update with Axios Mongoose

我正在嘗試設置編輯功能來編輯帖子。 現在我正在嘗試按 ID 更新特定帖子,然后我將使其動態化。

我可以讓 axios 發送 PUT 請求,但我沒有收到任何跡象表明它已在路由器上收到。 此外,我設置的 ID 在 URL 中正確顯示。

我不確定如何將數據發送到路由器,以便它可以找到 ID。

編輯組件

function handleSubmit(event){
        event.preventDefault()
        axios ( {
            url: `/api/${props.data[0]._id}`,
            method: 'PUT',
           headers: { "Content-Type": "multipart/form-data" },
            id: props.data[0]._id
        })
        .then(() => {
            console.log(`data has been sent to the server from axios: ${props.data[0]._id}`)
        })
        .catch(() => {
            console.log('Data could not be sent from axios')
        })

    } 

路由器

 router.put('/:id', async (req, res) => {
      try {
    
        const updatedGratitude = await PostGratitude.findByIdAndUpdate(req.params.id)
    
        res.status(200).json(updatedGratitude)
    
      } catch (err){
    
        next(err)
    
    }
    })

這是因為您忘記了方法的更新主體。 嘗試這個:

PostGratitude.findByIdAndUpdate(req.params.id, req.body)

代替:

await PostGratitude.findByIdAndUpdate(req.params.id)

因為mongoose不知道要更新什么:D

如果您正在編輯帖子,那么您應該在請求中發送數據以及標題:“”和描述:“”或其他內容,並且在路由器中,您可以編寫如下內容:

function handleSubmit(event) {
event.preventDefault()
axios({
    url: `/api/${props.data[0]._id}`,
    method: 'PUT',
    headers: { "Content-Type": "application/json" },
    data: {
        title: '',
        description: ''
    }
})
    .then((response) => {
        console.log(response)
    })
    .catch((err) => {
        console.log(err)
    })

}

您還需要通過 arguments 來了解要更新的內容,這是我編寫的代碼示例

router.put('/updatentry/:id',fetchuser, async (req, res) => {
var success = false
try {
    const { title, description } = req.body
    let newentry = { title: title , description: description
     }
    

    let old_entry = await Journal.findById(req.params.id);
    if (!old_entry) {
        return res.status(404).send({ success, error: 'Not Found'})
    }
    
    const update_entry = await Journal.findByIdAndUpdate(req.params.id, { $set: newentry }, { new: true })
    return res.send(res: update_entry)
} catch (error) {
    return res.status(500).send(error: 'Internal Server Error')
}

})

暫無
暫無

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

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