tony.0919 tony.0919 -3 years ago 177
Ajax Question

CSRF token mismatch for ajax post using nodejs express

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

In controllers/products/index.js

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

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

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

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

var _id =;
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.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download