3

Environment: express 4, jquery, krakenjs, font-awesome

In controllers/products/index.js

module.exports = function (router) {
    router.post('/add',function(req,res){
        // do something
    });
};

In the html file, users click the icon and add the products into the cart

{?products}
    {#products}
        <ul id="{.id}">
            <li class="add"><i class="fa fa-plus"></i></li>
        </ul>
    {/products}
{/products}

For each product, the following script is to do the ajax post to backend.

$('.add').click(function(e){
       var _id = this.parentElement.id;
       $.ajax({
           url: "/products/add",
           type: 'POST',
           contentType: 'application/json',
           dataType: 'json',
           data: JSON.stringify({
             id: _id
           })
       });
 });

The server then responds 500 (Internal Server Error) and states 'Error: CSRF token mismatch'. Do I need to insert the csrf token in ajax post or eliminate the token validation when doing ajax call without a form submission.

tony.0919
  • 1,145
  • 5
  • 16
  • 27

3 Answers3

4

Krakenjs uses Lusca for crsf protection.

Lusca stores the crsf _token in req.locals.

Also, set the crsf token in the view as a hidden / data-attribute and include that as a part of the ajax post.

Swaraj Giri
  • 4,007
  • 2
  • 27
  • 44
  • Is it a good practice to store the csrf in meta tag, then add a header `X-CSRF-Token` before ajax call is made ? i.e. `` – tony.0919 Apr 10 '15 at 06:49
  • Don't think so. Post another question about it. And if the answer solved your problem, mark it as accepted – Swaraj Giri Apr 10 '15 at 06:55
2

you should insert a csrf token in you ajax post.

if you use a express csrf middleware, then there would be a variable in the req, like req.csrfToken()(using csurf middleware) or something.

print this variable in the output html and use javascript to get it.

For best practice,

  1. make this variable a front-end global variable. so we can retrieve it easily.
  2. set csrf token in ajax header but not in form data. and register this behavior to jquery event. see http://erlend.oftedal.no/blog/?blogid=118
alsotang
  • 1,520
  • 1
  • 13
  • 15
0

You need to add a header "X-XSRF-TOKEN" with the proper TOKEN to you POST request.

This worked for me:

$.ajaxSetup({
        beforeSend: function (xhr) {
          xhr.setRequestHeader("X-XSRF-TOKEN", $cookies.get("XSRF-TOKEN"));
        }
      });

$.ajax({
        type: "POST",
        url: "/api/endpoint",
        data: formData, 
        cache: false,
        contentType: false,
        processData: false,
        success: function(data)
        {
          alert(data); // show response from the upload response.
        }
      });