rails - “WARNING: Can't verify CSRF token authenticity” for json devise requests

前端 未结 10 2167
终归单人心
终归单人心 2020-11-27 10:11

How can I retrieve the CSRF token to pass with a JSON request?

I know that for security reasons Rails is checking the CSRF token on all the request types (including

10条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-27 10:47

    This answer is better.

    You get to keep the CSRF-TOKEN validation with no extra effort (the token is appended) before any XMLHttpRequest send. No JQuery, no nothing just copy/paste and refresh.

    Simply add this code.

    (function() {
        var send = XMLHttpRequest.prototype.send,
            token = $('meta[name=csrf-token]').attr('content');
        XMLHttpRequest.prototype.send = function(data) {
            this.setRequestHeader('X-CSRF-Token', token);
            return send.apply(this, arguments);
        };
    }());
    

提交回复
热议问题