lokhi lokhi - 17 days ago 9
Ajax Question

Rails Can't verify CSRF token authenticity ajax with X-CSRF-TOKEN header

I try to register a service worker endpoint in my database but when I send my post data with fetch the app raise an error.

I want to keep the csrf verification. Do you see something wrong ?

var ready;

ready = function(){
if ('serviceWorker' in navigator) {
console.log('Service Worker is supported');
navigator.serviceWorker.register('/service-worker.js').then(function(reg) {

reg.pushManager.subscribe({
userVisibleOnly: true
}).then(function(sub) {
console.log('endpoint:', sub.endpoint);
console.log(sub);
var token = $('meta[name=csrf-token]').attr('content')
console.log(token);

return fetch('/register_endpoint', {
method: 'post',
headers: {
'Content-type': 'application/json',
'X-CSRF-TOKEN': token
},
body: JSON.stringify({
endpoint: sub.endpoint,
authenticity_token: token

})
});
});


}).catch(function(err) {
console.log('Erreur -> ', err);
});
}

};



$(document).ready(ready);
$(document).on('page:load',ready);


thanks

Answer

Instead of fetch i could suggest to make it like below:

$.ajax({ url: '_URL_HERE',
  type: 'POST',
  beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))},
  data: 'someData=' + someData,
  success: function(response) {
    $('#someDiv').html(response);
  }
});
Comments