[英]Using axios POST Request to Update JSON
我對 React 很陌生,目前正試圖弄清楚如何使用 axios.post 請求更新 JSON 文件。 我有一個功能,用戶可以上傳照片,目標是將該照片的 ID 和 imgURL 添加到 photos.json,我將在其中存儲該數據。 這是我的帖子 function:
axios.post('/api/photos', image)
.then(res => {
console.log(res.data);
})
.catch(function (error) {
console.log(error);
})
}
我在我的照片 controller 中發布了創建 function 的發布路線,如下所示:
module.exports.create = (req, res) => {
const photo = new Photo({
id: req.body.id,
imgURL: req.body.imgURL
})
photo.save()
.then((resp) => {
send_code_success(res,201, "photo save success");
})
.catch((err) => {
send_code_error(res,500, "photo save error");
console.error("Could not save photo to database:", err);
})
};
這就是我猜測問題所在,因為老實說,我不確定 go 應該在這里使用什么代碼。 任何幫助,將不勝感激!!!
在您創建 function 時,您需要將保存的文檔作為 JSON 返回到您的前端,以便您的前端可以使用它
axios.post('/api/photos', image).then(res => { console.log(res.data); //=>consume your JSON response }).catch(function (error) { console.log(error); }) module.exports.create = (req, res) => { const photo = new Photo({ id: req.body.id, imgURL: req.body.imgURL }) photo.save().then((resp) => { //send_code_success(res,201, "photo save success"); return res.status(200).json(resp) //=> return your saved doc to front end }).catch((err) => { send_code_error(res,500, "photo save error"); console.error("Could not save photo to database:", err); }) };
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.