[英]How to send csrf token in AJAX request (Without Jquery) in expressjs?
I am using the csurf module in expressjs. 我在expressjs中使用csurf模块。 It works for all post requests as I use it the following way.
它适用于所有发布请求,因为我使用以下方式。
app.use(csrf());
res.locals.csrfToken = req.csrfToken();
This way its automatically available in all forms where I have the following. 这样它可以自动提供所有形式,我有以下内容。
<input type="hidden" name="_csrf" value="<%=csrfToken%>">
but how do I set the csrftoken on AJAX requests, I am not using jquery, below is the JS function to send AJAX request. 但是如何在AJAX请求上设置csrftoken,我不使用jquery,下面是JS函数发送AJAX请求。 I do have the csrf token available on the html as a hidden value that I have access via getElementByID.
我确实在html上提供了csrf令牌作为隐藏值,我可以通过getElementByID访问它。
note: I am able to send the request if I disable csrf. 注意:如果禁用csrf,我可以发送请求。
function voteQuestion () {
var qid = document.getElementById("qid").value;
var csrf = document.getElementById("csrf").value;
var http = new XMLHttpRequest();
var url = "/q/ajaxcall";
var params = "qid="+ qid;
http.open("POST", url);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function() {
if(http.readyState == XMLHttpRequest.DONE && http.status == 200) {
var json = (http.responseText);
var obj = JSON.parse(json);
document.getElementById("vote-sp").innerHTML = (obj.upvotes);
}
};
http.send(params);
} }
Set crsf
token in your params
as below.. 在你的
params
设置crsf
令牌,如下所示。
var params = "qid="+ qid + "&crsf="+csrf;
OR 要么
You can create a new object for sending data as below.. 您可以创建一个新对象来发送数据,如下所示。
var data = {}; //crates new object
data.qid = qis; //adds qid to object
data.csrf = csrf; //adds qid to object
params = data; // to server
我一直试图解决这个问题差不多一个星期了,刚刚决定使用console.log req.session并发现cookies包含“XSRF-TOKEN”值,因此在AJAX请求标题中我将XSRF-TOKEN设置为csrf,现在它工作,我不知道为什么它以这种方式工作,特别是对于AJAX请求。
setRequestHeader("XSRF-TOKEN", csrf);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.