新手问题 [已解决] 提交使用 js 动态创建的表单,如何添加 CSRF_TOKEN?

deathking · 2014年08月28日 · 最后由 DeathKing 回复于 2014年08月29日 · 12870 次阅读

因为某些原因,我需要用 js 创建一个 form,然后自行提交,但是遇到InvalidAuthenticityToken

不是 Ajax 提交。关键代码如下,页面里面有个 button,然后点击时执行testPost()

// from https://stackoverflow.com/questions/133925/javascript-post-request-like-a-form-submit
function post(path, params, method) {
    method = method || "post"; // Set method to post by default if not specified.

    // The rest of this code assumes you are not using a library.
    // It can be made less wordy if you use one.
    var form = document.createElement("form");
    form.setAttribute("method", method);
    form.setAttribute("action", path);

    for(var key in params) {
        if(params.hasOwnProperty(key)) {
            var hiddenField = document.createElement("input");
            hiddenField.setAttribute("type", "hidden");
            hiddenField.setAttribute("name", key);
            hiddenField.setAttribute("value", params[key]);

            form.appendChild(hiddenField);
         }
    }

    document.body.appendChild(form);
    form.submit();
}

function testPost() {
    post("/books", {foo: "bar"});
}

解决方案:

在 post 中加入authenticity_token项,其值是 head 中的元数据 csrf-token 的值(由 Rails 生成)。

var token = $('meta[name="csrf-token"]').attr('content');

CSRF_TOKEN 在 html 的 head 中,用 js 抽取 或者 直接禁用 CSRF_TOKEN

#1 楼 @hardywu 我的意思是,抽取的话应该放在哪里?我 google 过,Ajax 请求的话,Rails 会自动抽取 token 放到 Request 里面。但是我这种方式我就不太清楚了。

实际上我比较疑惑的是,document.body.appendChild(form);明显是把我创建的 form 放在了原网页中再提交的,按理说还是有 CSRF_TOKEN 的啊!

为什么不用 $.post

#3 楼 @flowerwrong 看了你的代码,豁然开朗。确实有效,感激不尽!

需要 登录 后方可回复, 如果你还没有账号请 注册新账号