CSRF InvalidAuthenticityToken 与 Rails 和 React

2023-12-23

我无法让我的代码与 CSRF 令牌一起使用。

我有一个 axiosconfig 文件,我在其中设置 axios 并将其导出:

import axios from 'axios'

const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content')
const instance = axios.create({
  baseURL: 'http://api.domain.tld/v1/',
  headers: {
    'X-CSRF-Token': csrfToken
  }
});

export default instance

以及我导入它的反应组件:

import axios from '../config/axios'

在我提交的表单中,我解雇了这篇文章:

axios
  .post('/test', {
    longUrl: this.state.testValue
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

my head looks like this: enter image description here

the request what axios is posting is this: enter image description here

请求标头和我的头中的 CSRF 令牌是相同的,但我的 Rails-app 响应错误 422(不可处理的实体)并且:

ActionController::InvalidAuthenticityToken

是否有可能是这个问题:

  // `xsrfCookieName` is the name of the cookie to use as a value for xsrf token
  xsrfCookieName: 'XSRF-TOKEN', // default

  // `xsrfHeaderName` is the name of the http header that carries the xsrf token value
  xsrfHeaderName: 'X-XSRF-TOKEN', // default

我的 /v1/test 看起来像这样:

class Api::V1::IndexController < ApplicationController
  def test
    render :json => params
  end
end

或者是我的 config/application.rb 中的某些内容:

require_relative 'boot'

require 'rails/all'

# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)

module TestAppForMe
  class Application < Rails::Application
    # Initialize configuration defaults for originally generated Rails version.
    config.load_defaults 5.1

    # Settings in config/environments/* take precedence over those specified here.
    # Application configuration should go into files in config/initializers
    # -- all .rb files in that directory are automatically loaded.

    config.middleware.insert_before 0, Rack::Cors do
      allow do
        origins '*'
        resource '*', :headers => :any, :methods => [:get, :post, :options]
        # resource '*',
        #   headers: ['Origin', 'Accept', 'Content-Type', 'X-CSRF-Token'],
        #   :methods => [:get, :post, :options]
      end
    end
  end
end

在我的路线中我有这样的东西:

constraints subdomain: "api" do
    scope module: "api" do
      namespace :v1 do
        root 'index#index'
      end
    end
  end

None

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

CSRF InvalidAuthenticityToken 与 Rails 和 React 的相关文章

随机推荐