简体   繁体   中英

sending cookies with ajax request via fetch api

In a nodeJs app, i am sending multipart/form-data to the server via ajax request. I am also using csurf package to guard against csrf attacks

Problem

When i submit my form without ajax request, everything works fine but when i submit my form using ajax request, i get invalid csrf token error on the server.

As far as i have understood the cause of this error, its because of cookies not sent with the request.

To send the cookies with ajax request, i set credentials: 'same-origin' in the post request made via fetch api but that didn't fix the issue. I also tried setting credentials: 'include' but that didn't make any difference.

Question

Is my understanding correct that this issue is because of cookies not being sent with ajax request and how can i fix this issue?

Code

let response = await fetch(requestUrl, {
      method: 'POST',
      credentials: 'include',
      headers: {
          'Content-Type': 'multiplart/form-data'
      },
      body: new URLSearchParams(form)
});

When using fetch() /AJAX with csurf , you need to pass the CSRF token as a request header:

// Read the CSRF token from a hidden input in the form
const token = document.querySelector('input[name="csrf-token"]').value;

// POST using the Fetch API
fetch('/<route.name>', {
  headers: {
    // pass the csrf token as a header
    'CSRF-Token': token
  },
  method: 'POST',
  body: {
    ...
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM