I have an app which uses Rails and React. The AJAX in rails part works fine but I have some components in React which use AJAX and the error occurs in the AJAX requests through React components.
I get the following error:
2017-10-17T15:36:26.933083+00:00 app[web.1]: [14b2fc9e-80b7-490f-b905-
5be9f6839c5b] Started POST "/quiz_submissions" for 162.158.165.188 at 2017-10-17 15:36:26 +0000
2017-10-17T15:36:26.935109+00:00 app[web.1]: [14b2fc9e-80b7-490f-b905-
5be9f6839c5b] Processing by QuizSubmissionsController#create as JSON
2017-10-17T15:36:26.935151+00:00 app[web.1]: [14b2fc9e-80b7-490f-b905-5be9f6839c5b] Parameters: {"quiz_submission"=>{"quiz_problem_id"=>"21", "checked_option_ids"=>["88"]}}
2017-10-17T15:36:26.935688+00:00 app[web.1]: [14b2fc9e-80b7-490f-b905-5be9f6839c5b] Can't verify CSRF token authenticity.
2017-10-17T15:36:26.936459+00:00 app[web.1]: [14b2fc9e-80b7-490f-b905-5be9f6839c5b] Completed 422 Unprocessable Entity in 1ms (ActiveRecord: 0.0ms)
2017-10-17T15:36:26.937451+00:00 app[web.1]: [14b2fc9e-80b7-490f-b905-5be9f6839c5b]
2017-10-17T15:36:26.937485+00:00 app[web.1]: [14b2fc9e-80b7-490f-b905-5be9f6839c5b] ActionController::InvalidAuthenticityToken (ActionController::InvalidAuthenticityToken):
I've tried adding the CSRF Token in ajax header by adding this to my main.js
$.ajaxSetup({
beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token',
$('meta[name="csrf-token"]').attr('content'))},
});
This works completely fine on my local machine but gives the same error on production environment(Heroku).
Alternatively, I've also tried adding the CSRF Token in the header of individual ajax requests inside the React Component as follows:
$.ajax({
dataType: 'JSON',
type: 'POST',
url: '/quiz_submissions',
context: this,
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
},
data: {
...
}
}
This approach also works fine locally but gives the same Can't verify CSRF token authenticity.
error on production.
I have <%= csrf_meta_tags %>
on my head section and I also have //= require jquery_ujs
on my application.js
Any idea why it doesn't work on production environment on Heroku?