CSRF InvalidAuthenticityToken带有rails并做出反应

时间:2017-12-17 17:59:14

标签: ruby-on-rails reactjs axios

我无法使用CSRF-Token处理我的代码。

我有一个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);
  });

我的脑袋看起来像这样: enter image description here

axios发布的请求是: enter image description here

来自请求标头的CSRF-Tokens和我的头是相同的但是我的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

my / 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

0 个答案:

没有答案