I can't get my code working with the CSRF-Token.
I have a axiosconfig file where I setup axios and export it:
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
and my react component where I import it:
import axios from '../config/axios'
in my form on submit I fire this Post:
axios
.post('/test', {
longUrl: this.state.testValue
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
my head looks like this:
the request what axios is posting is this:
the CSRF-Tokens from the request-header and my head are the same but my rails-app respons with error 422 (Unprocessable Entity) and:
ActionController::InvalidAuthenticityToken
is it possible that something with this is the problem:
// `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 looks like this:
class Api::V1::IndexController < ApplicationController
def test
render :json => params
end
end
Or is it something in my 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
in my routes I've something like this:
constraints subdomain: "api" do
scope module: "api" do
namespace :v1 do
root 'index#index'
end
end
end