1

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

}

1
  • You can use FormData() object to send a full form data with CsrfToken. Commented Jan 3, 2017 at 5:23

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

Comments

0

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

3 Comments

tried both, still get ForbiddenError: invalid csrf token. I also tried "&_csrf" since csurf uses that as it's name value, still does not work. plus tried setRequestHeader('X-CSRF-Token', csrf), this also does not work.
check value in server file using $_POST['csrf'];
I cannot send the request , so I cannot check it. I am using express and have a console.log on my router.post("/q/ajaxcall") and the request does not even get until that point.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.