简体   繁体   中英

How to send csrf token in AJAX request (Without Jquery) in expressjs?

I am using the csurf module in expressjs. 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. I do have the csrf token available on the html as a hidden value that I have access via getElementByID.

note: I am able to send the request if I disable 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..

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM