How to add assign csrf token in the HTML submit form

霸气de小男生 提交于 2019-12-10 19:13:57

问题


My site is under csurf protection at the moment.

I have assigned all my ajax call with csrf token like below

"/data/someAPI?_csrf="+ $("#_csrf").val and it works just fine with all function I had.

But now I am writing a file upload function and most of the tutorials on the internet are using sumbit form to do so.

So I wrote something like

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

Solved

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>

I directly assigned the token in the form action and it works fine.


回答1:


You can add hidden field for _csrt token. Here is example code

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


来源:https://stackoverflow.com/questions/47527120/how-to-add-assign-csrf-token-in-the-html-submit-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!