React 使用 axios.put 的时候,反馈 Can't verify CSRF token authenticity

lukefan · July 29, 2017 · Last by lukefan replied at August 02, 2017 · 8417 hits

Started PUT "/products/597074f958efe52639ad261a" for 127.0.0.1 at 2017-07-29 00:17:11 +0800 Processing by ProductsController#update as HTML Parameters: {"title"=>"abc", "desc"=>"hehe", "id"=>"597074f958efe52639ad261a", "product"=>{"title"=>"abc", "desc"=>"hehe"}} Can't verify CSRF token authenticity. Completed 422 Unprocessable Entity in 1ms

ActionController::InvalidAuthenticityToken (ActionController::InvalidAuthenticityToken):

我用 react 写了个例子。 get 信息的时候没有问题,但是 put 的时候,就 422 了。

我尝试了添加:axios.defaults.headers.common['Authorization'] = 'L2yn79biL79xYPVV7N3997FEyLUeN9Av7DfweSocco4ircVzTs+qli8tcVgd8Hx+Y2CNRgFAPrMLAFrOxoCRsg=='; 在代码中,依然无效。 请问应该怎么解决 token 的问题?

关了 rails 自带的 csrf

Reply to pathbox

是的,应该如何处理呢? 我没有办法取得 $('meta[name="csrf-token"]').attr('content')。 有什么方法可以获得独立的 token 吗?

调整了一下,解决了问题。 先在 application_controller.rb 里面把

protect_from_forgery with: :exception

注释掉,算是把逻辑调整完成了。

然后在 js 里面加上了:

axios.defaults.headers.common['X-CSRF-Token'] = document.getElementsByTagName("meta")[1].content;

再恢复 application_controller.rb 里面的

protect_from_forgery with: :exception

工作正常。

作为一个把写程序作为业余爱好的业余程序员,经常会遇到很多稀奇古怪的问题,在慢慢解决问题的过程中,寻找乐趣。

Reply to lukefan

好像做了第二步就不用再做第一步注释了,更安全一点

Reply to nong

做注释的时候,还没有找到正确的方法。在找到正确方法之后,就把注释取消了。

You need to Sign in before reply, if you don't have an account, please Sign up first.