ajax post 使用 nodejs express 的 CSRF 令牌不匹配

CSRF token mismatch for ajax post using nodejs express

环境:express 4,jquery,krakenjs,font-awesome

在controllers/products/index.js

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

在 html 文件中,用户单击图标并将产品添加到购物车

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

对于每个产品,下面的脚本是做ajax post到后端。

$('.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
           })
       });
 });

服务器然后响应 500(内部服务器错误)并声明 'Error: CSRF token mismatch'。我是否需要在 ajax post 中插入 csrf 令牌,或者在不提交表单的情况下执行 ajax 调用时消除令牌验证。

你应该在你里面插入一个 csrf 令牌 ajax post.

如果你使用 express csrf 中间件,那么 req 中会有一个变量,比如 req.csrfToken()(使用 csurf 中间件)或其他东西。

在输出中打印此变量 html 并使用 javascript 获取它。

为了获得最佳实践,

  1. 使该变量成为 front-end 全局变量。所以我们可以很容易地检索它。
  2. 在 ajax header 中设置 csrf 令牌,但不在表单数据中。并将此行为注册到 jquery 事件。见 http://erlend.oftedal.no/blog/?blogid=118

Krakenjs 使用 Lusca 用于 crsf 保护。

Lusca 将 crsf _token 存储在 req.locals 中。

此外,将视图中的 crsf 标记设置为隐藏/数据属性,并将其作为 ajax post.

的一部分

您需要为您的 POST 请求添加一个 header "X-XSRF-TOKEN" 和正确的令牌。

这对我有用:

$.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.
        }
      });