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);
}
I have been trying to figure this out for almost a week now, and just decided to console.log req.session and found cookies contains "XSRF-TOKEN" value, so in the AJAX request header I set XSRF-TOKEN to csrf and now it works, I dont know why it works this way particularly for AJAX requests.
setRequestHeader("XSRF-TOKEN", csrf);