gpt4 book ai didi

javascript - 使用 axios POST 请求更新 JSON

转载 作者:行者123 更新时间:2023-12-02 21:03:42 25 4
gpt4 key购买 nike

我对 React 很陌生,目前正在尝试弄清楚如何使用 axios.post 请求更新 JSON 文件。我有一个功能,用户可以上传照片,目标是将照片的 ID 和 imgURL 添加到 photos.json,我在其中存储该数据。这是我的帖子功能:

            axios.post('/api/photos', image)
.then(res => {
console.log(res.data);
})
.catch(function (error) {
console.log(error);
})
}

我在照片 Controller 中发布了创建功能的路由,如下所示:

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

这就是我猜测问题所在的地方,因为说实话,我不确定这里应该放什么代码。任何帮助将不胜感激!!!

最佳答案

在创建函数中,您需要将保存的文档作为 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);
})
};

关于javascript - 使用 axios POST 请求更新 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61276738/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com