在 nodeJs 应用程序中,我multipart/form-data
通过 ajax 请求发送到服务器。我也在使用csurf
包来防范csrf
攻击
问题
当我在没有 ajax 请求的情况下提交表单时,一切正常,但是当我使用 ajax 请求提交表单时,我invalid csrf token
在服务器上出现错误。
据我了解此错误的原因,是因为 cookie 未随请求一起发送。
要使用Ajax请求发送的cookie,我设置credentials: 'same-origin'
在post
通过提出请求,fetch api
但没有解决问题。我也尝试过设置,credentials: 'include'
但这没有任何区别。
问题
我的理解是否正确,这个问题是因为 cookie 没有与 ajax 请求一起发送,我该如何解决这个问题?
代码
let response = await fetch(requestUrl, {
method: 'POST',
credentials: 'include',
headers: {
'Content-Type': 'multiplart/form-data'
},
body: new URLSearchParams(form)
});
将fetch()
/AJAX 与 一起使用时csurf
,您需要将 CSRF 令牌作为请求标头传递:
// Read the CSRF token from a hidden input in the form
const token = document.querySelector('input[name="csrf-token"]').value;
// POST using the Fetch API
fetch('/<route.name>', {
headers: {
// pass the csrf token as a header
'CSRF-Token': token
},
method: 'POST',
body: {
...
}
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句