新手问题 ajax post 出现 InvalidAuthenticityToken

saiga · 2013年11月08日 · 最后由 saiga 回复于 2013年11月08日 · 3405 次阅读

用的是 $.post,已经引入 jquery_ujs

prom = $.post '/capvalid', value: value, key: $('#captcha_key').val()
prom.done (resp) =>
  if resp.pass
    @cCaptcha.addClass 'has-success'
    @enable()
  else
    @cCaptcha.addClass 'has-error'

正常进入页面是正常的。

但是,关掉 chrome 再用还原标签页那个功能,post 带的那个 token 对不上。

问题很明确啊,你 POST 过去的数据中,一定要带 authenticity_token 的。

在 capvalid 的 controller 里边可以加上这句就会自动跳过验证,但可能降低安全性。 skip_before_filter :verify_authenticity_token, :only => :capvalid

在 application.js 里 带上这段

$.ajaxSetup({
    beforeSend: function (xhr) {
        xhr.setRequestHeader('X-CSRF-Token',
            $('meta[name="csrf-token"]').attr('content'));
    }
});

#1 楼 @libuchao 有 authenticity_token,但是对不上。

#2 楼 @raofeng 已经换成 get 请求了。不过我还是想知道为什么 authenticity_token 在还原标签后会对不上。

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