Multer和CSRF和

问题描述 投票:1回答:1

所以,我刚刚为我的项目添加了multer和cloudinary。每当我使用我的表单向我的数据库添加内容。它给出了这个错误“ForbiddenError:invalid csrf token”

但我通过在我的表单中添加?_csrf=<%= csrfToken %>"到我的action属性来解决这个问题

<form action="/admin?_csrf=<%= csrfToken %>" method="POST" enctype="multipart/form-data">

现在,我正在尝试为我的更新路线做同样的事情。并且它在“ForbiddenError:invalid csrf token”之前给出了同样的错误

我试过做<form action="/admin/<%= prod._id %>?_method=PUT?_csrf=<%= csrfToken %>" method="POST" enctype="multipart/form-data">

或这个

<form action="/admin/<%= prod._id %>?_method=PUT?_csrf=<%= csrfToken %>" method="POST" enctype="multipart/form-data">

或这个

<form action="/admin/<%= prod._id %>?_method=PUT_csrf=<%= csrfToken %>" method="POST" enctype="multipart/form-data">

或这个

<form action="/admin/<%= prod._id %>?_csrf=<%= csrfToken %>_method=PUT" method="POST" enctype="multipart/form-data">

你知道......不同的变化...希望一个人会工作。 HAHAH

无论如何,我正在做什么不可能?我的动作属性中可以有2个方法吗?

还有另外一种方法我可以这样做吗?

Edit.ejs

<section class="no-padding-top">
  <div class="container-fuid">
    <div class="row">
      <div class="col-lg-12">
        <div class="block">
        <div class="title"><strong>Edit Item</strong></div>
          <form action="/admin/<%= prod._id %>?_method=PUT" method="POST" enctype="multipart/form-data">
           <div class="form-group row">
              <label class="col-sm-3 form-control-label">Product Name</label>
              <div class="col-sm-9">
              <input type="text" class="form-control" name="prod[name]" value="<%= prod.name %>" required>
              </div>
            </div>
            <div class="form-group row">
              <label for="image" class="col-sm-3 form-control-label">Product Image</label>
              <div class="col-sm-9">
              <input type="file" id="image" name="image" accept="image/*" >
              </div>
            </div>
            <div class="form-group row">
              <label class="col-sm-3 form-control-label">Product Price</label>
              <div class="col-sm-3">
              <input type="text" class="form-control" name="prod[price]" value="<%= prod.price %>" required>
              </div>
              <label class="col-sm-1 form-control-label">Product Quantity</label>
              <div class="col-sm-2">
              <input type="text" class="form-control" name="prod[quantity]" value="<%= prod.quantity %>" required>
              </div>
            </div>
            <div class="form-group row">
              <label class="col-sm-3 form-control-label">Product Brand</label>
              <div class="col-sm-3">
              <input type="text" class="form-control" name="prod[brand]" value="<%= prod.brand %>"  required>
              </div>
              <label class="col-sm-1 form-control-label">Product type</label>
              <div class="col-sm-2">
              <input type="text" class="form-control" name="prod[type]" placeholder="Types of produces. i.e Wheels, Lights, Steering Wheels..." value="<%= prod.type %>" required>
              </div>
            </div>
            <div class="form-group row">
              <label class="col-sm-3 form-control-label">Product Description</label>
              <div class="col-sm-9">
              <textarea cols="30" rows="10" class="form-control" name="prod[description]" required> <%= prod.description%> </textarea>
              </div>
            </div>
            <div class="form-group row">
              <div class="col-sm-9 ml-auto">
                <button type="submit" class="btn btn-primary">Edit Item</button>
                <a href="/admin" class="btn btn-info ml-3">Cancel</a>
              </div>
            </div>
            <input type="hidden" name="_csrf" value="<%= csrfToken %>">
          </form>
        </div>
      </div>
    </div>
  </div>
</section>

m and和cloudinary开始

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 cloudinary = require('cloudinary');
cloudinary.config({ 
  cloud_name: 'pitscaraccessories', 
  api_key: process.env.CLOUDINARY_API_KEY, 
  api_secret: process.env.CLOUDINARY_API_SECRET
});

更新路线

router.put("/:id", middleware.isLoggedIn, middleware.isAdmin, upload.single('image'), function(req, res) {
    Product.findById(req.params.id, async function(err, prod) {
        if (err) {
            req.flash("error", err.message);
        } else {
            if (req.file) {
                try {

                    await cloudinary.v2.uploader.destroy(prod.imageId);
                    var result = await cloudinary.v2.uploader.upload(req.file.path);
                    prod.image = result.secure_url;
                    prod.imageId = result.public_id;

                } catch (err) {
                    req.flash("error", err.message);
                    return res.redirect("back");
                }
            }

            prod.save();

            req.flash("success", "Updated Successfully");
            res.redirect("/admin");
        }
    });
});
node.js express csrf multer cloudinary
1个回答
1
投票

通过对我的代码执行此操作来修复此问题改变了我从.put.post的路线

并手动更新内部的每个输入。

router.post("/:id", middleware.isLoggedIn, middleware.isAdmin, upload.single('image'), function(req, res) {
    Product.findById(req.params.id, async function(err, prod) {
        if (err) {
            req.flash("error", err.message);
        } else {
            if (req.file) {
                try {
                    await cloudinary.v2.uploader.destroy(prod.imageId);
                    var result = await cloudinary.v2.uploader.upload(req.file.path);
                    prod.image = result.secure_url;
                    prod.imageId = result.public_id;
                } catch (err) {
                    req.flash("error", err.message);
                    return res.redirect("back");
                }
            }

            prod.name = req.body.name;
            prod.price = req.body.price;
            prod.quantity = req.body.quantity;
            prod.brand = req.body.brand;
            prod.type = req.body.type;
            prod.description = req.body.description;

            prod.save();

            req.flash("success", "Updated Successfully");
            res.redirect("/admin");
        }
    });
});

并对我的表单元素执行此操作

<form action="/admin/<%= prod._id %>?_csrf=<%= csrfToken %>" method="POST" enctype="multipart/form-data">

© www.soinside.com 2019 - 2024. All rights reserved.