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

Viewed 2126

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

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

I got it working now the answer above didnt work i had to stringfiy body data

    (async function fetchUsers(){
    var datas = {
    'title':'test'
    }
    const resOne = await fetch('http://localhost/elementor_barba/wp-json/wp/v2/posts/1',{
        method : 'POST',
        headers : {
         'Content-Type': 'application/json',
          'X-WP-Nonce' :  universityData.nonce // here you used the wrong name
        },
        credentials: 'same-origin',
        body:JSON.stringify(datas)
        
       
    })
    const dataOne = await resOne.json()
    

    console.log(dataOne)

})()
Related