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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With