如何在 HTML 提交表单中添加分配 csrf 令牌

How to add assign csrf token in the HTML submit form

我的站点目前受 csurf 保护。

我已经为所有 ajax 通话分配了 csrf 令牌,如下所示

"/data/someAPI?_csrf="+ $("#_csrf").val 它与我拥有的所有功能都能正常工作。

但是我现在正在写一个文件上传功能,网上的大部分教程都是用sumbit形式来做的。

所以我写了类似

的东西

Node.js

app.post('/upload', function(req, res) {
  if (!req.files)
    return res.status(400).send('No files were uploaded.');

  // The name of the input field (i.e. "sampleFile") is used to retrieve the uploaded file
  let sampleFile = req.files.sampleFile;

  // Use the mv() method to place the file somewhere on your server
  sampleFile.mv('/somewhere/on/your/server/filename.jpg', function(err) {
    if (err)
      return res.status(500).send(err);

    res.send('File uploaded!');
  });
});

已解决

HTML

<html>
  <body>
    <form ref='uploadForm' 
      id='uploadForm' 
      action='http://localhost:8000/upload?_csrf=<your_csrf_token>"' 
      method='post' 
      encType="multipart/form-data">
        <input type="file" name="sampleFile" />
        <input type='submit' value='Upload!' />
    </form>     
  </body>
</html>

我直接在表单操作中分配了令牌,它工作正常。

您可以为 _csrt 令牌添加隐藏字段。这是示例代码

<html>
  <body>
    <form ref='uploadForm' 
      id='uploadForm' 
      action='http://localhost:8000/upload' 
      method='post' 
      encType="multipart/form-data">
        <input type="file" name="sampleFile" />
        <input type="hidden" name="_csrf" value="<your_csrf_token>" />
        <input type='submit' value='Upload!' />
    </form>     
  </body>
</html>