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

Ans*_*pta 6 javascript ajax jquery csrf

我的网站目前受到 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!');
  });
});
Run Code Online (Sandbox Code Playgroud)

解决了

超文本标记语言

<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>
Run Code Online (Sandbox Code Playgroud)

我直接在表单操作中分配了令牌,效果很好。

Bha*_*nki 4

您可以为_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>
Run Code Online (Sandbox Code Playgroud)