javascript 如何在 HTML 提交表单中添加分配 csrf 令牌
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47527120/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add assign csrf token in the HTML submit form
提问by Anson A?tepta
My site is under csurf protection at the moment.
我的网站目前受 csurf 保护。
I have assigned all my ajax call with csrf token like below
我已经用 csrf 令牌分配了我所有的 ajax 调用,如下所示
"/data/someAPI?_csrf="+ $("#_csrf").valand it works just fine with all function I had.
"/data/someAPI?_csrf="+ $("#_csrf").val它适用于我拥有的所有功能。
But now I am writing a file upload function and most of the tutorials on the internet are using sumbit form to do so.
但是现在我正在编写一个文件上传功能,并且互联网上的大多数教程都是使用 sumbit 形式来这样做的。
So I wrote something like
所以我写了类似的东西
Node.js
节点.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
<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.
我直接在表单操作中分配了令牌,它工作正常。
采纳答案by Bhavin Solanki
You can add hidden field for _csrttoken. Here is example code
您可以为_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>

