以下是我的代码,当我发送删除请求时,我一直在标题中收到错误。我只在下面包含了创建和删除路由。我不熟悉cloudinary,如果有人可以解释我的错误,我将不胜感激。我很高兴终于有一个部分工作的上传系统,但我真的想把它全部搞定并且完善,只是让删除工作会很棒。
var express = require("express");
var router = express.Router();
var Post = require("../models/post");
var middleware = require("../middleware");
// --------multer config
var multer = require('multer');
var storage = multer.diskStorage({
filename: function(req, file, callback) {
callback(null, Date.now() + file.originalname);
}
});
var imageFilter = function (req, file, cb) {
// accept image files only
if (!file.originalname.match(/\.(jpg|jpeg|png|gif)$/i)) {
return cb(new Error('Only image files are allowed!'), false);
}
cb(null, true);
};
var upload = multer({ storage: storage, fileFilter: imageFilter})
var apisecret ="*removed for safety*";
var cloudinary = require('cloudinary');
cloudinary.config({
cloud_name: 'dkjjx5pgg',
api_key: *removed for safety*,
api_secret: apisecret
});
// -------multer end
//CREATE - add new post to DB
router.post("/", middleware.isLoggedIn && middleware.isAdmin, upload.single('image'), function(req, res){
// get data from form and add to posts array
cloudinary.v2.uploader.upload(req.file.path, function(err, result) {
if(err) {
req.flash('error', err.message);
return res.redirect('back');
}
// add cloudinary url for the image to the post object under image property
req.body.post.image = result.secure_url;
// add image's public_id to post object
req.body.post.imageId = result.public_id;
// add author to post
req.body.post.author = {
id: req.user._id,
username: req.user.username
}
Post.create(req.body.post, function(err, post) {
if (err) {
req.flash('error', err.message);
return res.redirect('back');
}
res.redirect("/posts");
});
});
});
// DESTROY posts ROUTE
router.delete('/:id', function(req, res) {
Post.findById(req.params.id, async function(err, post) {
if(err) {
req.flash("error", err.message);
return res.redirect("/posts");
}
try {
await cloudinary.v2.uploader.destroy(post.imageId);
post.remove();
req.flash('success', 'Post deleted successfully!');
res.redirect('/posts');
} catch(err) {
if(err) {
req.flash("error", err.message);
return res.redirect("/posts");
}
}
});
});
module.exports = router;