How to make a fetch() POST request to wordpress rest api?

I am trying to make a POST request to rest api. But I am getting 401 Unauthorised error. Also can someone help with handling nonce in it?

#OurPostData : Contains the title.

fetch('https://mywebsite.online/wp-json/wp/v2/code',{
      method: 'POST',
      credentials: 'same-origin',
      headers: new Headers({'Content-Type': 'application/x-www-form-urlencoded'}),
      body:JSON.stringify(OurPostData),
    }).then(response => {
      console.log(response);
      return response.json();
    });

this method below works

var createPost = new XMLHttpRequest();
createPost.open("POST", "https://mywebsite.online/wp-json/wp/v2/code");
createPost.setRequestHeader("X-WP-Nonce", Ajax.nonce);
createPost.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
createPost.send(JSON.stringify(OurPostData));
createPost.onreadystatechange = function() {
  if (createPost.readyState == 4) {
    if (createPost.status == 201) {
      alert("Success");
    } else {
      alert("Error Try Again");
    }
  }
}

Thanks

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

'X-WP-Nonce' : Ajax.nonce Was missing that’s why it was giving the error

  fetch('https://mywebsite.online/wp-json/wp/v2/code', {
      method: 'POST',
      credentials: 'same-origin',
      headers: new Headers({
        'Content-Type': 'application/json;charset=UTF-8',
        'X-WP-Nonce' : Ajax.nonce
      }),
      body: JSON.stringify(OurPostData),
    }).then(response => {
      console.log(response);
      return response.json();
    });


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x