Multer和CSRF和<form action =“?_ method = PUT”>

时间:2019-02-17 15:12:02

标签: node.js express csrf multer cloudinary

因此,我在我的项目中添加了multer和cloudinary。 每当我使用表单向我的数据库添加一些东西时。它给出了这个错误 “ ForbiddenError:无效的CSRF令牌”

但是我已经通过在我的表单的action属性中添加class TupleObject(tuple): def __init__(self, property, _tuple): super().__init__(_tuple) self.property = property _tuple = TupleObject(property, (0, 0)) 来解决了这个问题

?_csrf=<%= csrfToken %>"

现在,我正在尝试对我的更新路线执行相同的操作。 并且给了我与“ ForbiddenError:无效的csrf令牌”之前相同的错误

我尝试做 <form action="/admin?_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 %>?_method=PUT_csrf=<%= csrfToken %>" method="POST" enctype="multipart/form-data">

您知道...其他种类的变化...希望有人能使用。哈哈

无论如何,我在做什么是不可能的?我的action属性中可以有2种方法?

还有另一种方式可以执行此操作吗?

Edit.ejs

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

多云和多云开始

<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>

更新路线

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

2 个答案:

答案 0 :(得分: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">

答案 1 :(得分:0)

我遇到了同样的问题,也许您没有尝试足够的排列; D

这种语法对我有用

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