4

Using the fetch API to make calls to the Rails server is causing a few problems that did not occur when using ajax.

  1. CSRF, with jquery the rails gem automatically places the CSRF token in requests, is there a way to accomplish a similar effect with fetch?

  2. Session cookie is not persisting page reloads. I am using a session token to store a current users session and logging in then refreshing wipes the session when it should be preserved.

Have been unable to find any resources on this subject, and I have used the exact same code successfully when making calls via ajax so I know the problem is related to my switch to fetch

nick
  • 241
  • 2
  • 13

1 Answers1

1
  1. I'm working on figuring this one out right now. I'll update this answer when I figure it out. But the basic idea is that you need to pass the 'X-CSRF-Token' header. You can get the csrf token using this code, if you're using jQuery:

    $('meta[name=csrf-token]').attr('content')
    
  2. By default, fetch doesn't include cookies. You have to pass this option: credentials: 'same-origin'. See this question: Fetch API with Cookie

Michael Hewson
  • 1,444
  • 13
  • 21