首页 > 解决方案 > 如何修复 CSRF 不匹配?

问题描述

我正在尝试使用 expressJS 通过我的 js 应用程序中的“axios”包运行对我正在使用的 API 的请求。

尽管令牌正确,但我只是不断收到“CSRF 令牌不匹配”,它使用 YARC google chrome 扩展程序工作,但在我的应用程序或邮递员中不起作用。

我正在使用的代码是:

    var options = {
        "method": "POST",
        "url": "https://example.com/lines/data",
        "headers": {
          "X-CSRF-TOKEN": "IZ1QTMDHl3D0HFkAPemC13 - removed some of token",
          "Accept": "application/json, text/plain, */*",
          "Content-Type": "application/json;charset=utf-8"
        },
        data: {
            'token': 'IZ1QTMDHl3D0HFkAPemC13 - removed some of token',
        }
    }
    request(options, function(err, response, body) {
        if(err) {
            if(err.code == "ETIMEDOUT" && err.connect == true) {
                res.status(500).json({status: "FAILED"})
                return;
            } else {
                console.log(err);
                res.status(500).json({status: "FAILED"})
                return;
            }
        }
        // var body = JSON.parse(body);

        res.send(body);
    })

它返回 "{ "message": "CSRF token mismatch." }"

使用带有 chrome 扩展的以下请求(https://chrome.google.com/webstore/detail/yet-another-rest-client/ehafadccdcdedbhcbddihehiodgcddpl?hl=en)工作正常并返回我的 json

{
  "method": "POST",
  "transformRequest": [
    null
  ],
  "transformResponse": [
    null
  ],
  "url": "https://example.com/lines/data",
  "headers": {
    "X-CSRF-TOKEN": "IZ1QTMDHl3D0HFkAPemC13 - removed some of token",
    "Accept": "application/json, text/plain, */*",
    "Content-Type": "application/json;charset=utf-8"
  },
  "data": "",
  "timeout": {}
}

标签: javascriptnode.js

解决方案


推荐阅读