lokhi lokhi - 1 year ago 100
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) {

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

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);




Answer Source

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) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download