Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to convert jquery AJAX to Fetch API, how to setRequestHeader?

I have jQuery AJAX call to Wordpress API and I need to set Nonce in requestHeader for authentication.

$.ajax({
  url: '/wp-json/app/v1/get_data/',
  method: 'POST',
  beforeSend: function ( xhr ) {
    xhr.setRequestHeader( 'X-WP-Nonce', NONCE ); // NONCE is global var
  },
  data: {},
}).done(onSuccess);

Then I want to convert that code to Fetch API, so I tried this:

window.fetch('/wp-json/app/v1/get_data/', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'X-WP-Nonce': NONCE
  },
  body: {},
}).then(onSuccess)

But I get 403 Forbidden as if my Nonce isn't detected. I'm not sure whether it is the right way to set requestHeader.

I can't find much info about Fetch API, so anyone have experience with this?

Thanks

like image 308
hrsetyono Avatar asked Oct 27 '25 05:10

hrsetyono


1 Answers

I solved it by adding credentials: 'same-origin' to the arguments

window.fetch('/wp-json/app/v1/get_data/', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'X-WP-Nonce': NONCE
  },
  credentials: 'same-origin',
  body: {},
}).then(onSuccess)
like image 94
hrsetyono Avatar answered Oct 28 '25 17:10

hrsetyono



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!