【发布时间】:2018-05-11 15:32:00
【问题描述】:
我的网站目前处于 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>
我直接在表单操作中分配了令牌,它工作正常。
【问题讨论】:
-
为什么不像你在
ajax电话中那样做呢?即以action的形式定义令牌。 -
@aquaman 你的意思是我应该 把这行放在表格里吗?
-
我的意思是将您的表单修改为
action="/upload?_csrf=<your_csrf_token>"。好吧,您可以尝试其他选项中的建议。 -
谢谢我解决了!!! @aquaman
-
小问题,你首先如何获得那个 CSRF 令牌?
标签: javascript jquery ajax csrf