【问题标题】:csrf in react and railsreact 和 rails 中的 csrf
【发布时间】:2020-09-21 03:09:24
【问题描述】:

我想在使用 post 请求时使用 csrf 令牌。为此,我在 api 控制器中使用了顶部的 protect_from_forgery with: :null_session

但是我应该如何在反应中使用它。

我也找不到任何关于此的好文章。

fetch('/api/v1/posts', {
      method: 'post',
      body: JSON.stringify(postdata),
      headers: { 'Content-Type': 'application/json' },
    })

【问题讨论】:

    标签: ruby-on-rails reactjs csrf


    【解决方案1】:

    据我了解,您需要在调用时将 X-CSRF-TOKEN 作为标头传递给 Rails。您可以使用document.querySelector('[name="csrf-token"]').content 获取令牌:

    这应该在您的componentDidMount 方法中:

       fetch('/api/v1/posts', {
          method: 'post',
          body: JSON.stringify(postdata),
          headers: {
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': document.querySelector('[name="csrf-token"]').content
          },
        })
    

    【讨论】:

    • 我正在使用 fetch
    • 嗯,好的,我建议将其放在问题中,以及您用于实际进行 fetch 调用的代码示例。
    猜你喜欢
    • 2020-02-20
    • 2010-12-22
    • 1970-01-01
    • 2018-03-29
    • 2018-02-06
    • 2019-07-15
    • 2013-10-08
    • 2021-04-30
    • 2014-11-21
    相关资源
    最近更新 更多