0

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

7
  • Lots of other people with this issue before - for example: wordpress.stackexchange.com/a/315731/7968
    – Q Studio
    Jan 9, 2021 at 13:29
  • 1
    Also, from the official documentation on authentication: developer.wordpress.org/rest-api/using-the-rest-api/…
    – Q Studio
    Jan 9, 2021 at 13:30
  • @QStudio is there a way to do it without that way? If I am making something for the public I can't ask for them to edit htaaccess file
    – user145078
    Jan 9, 2021 at 13:31
  • First, try and see if this is the issue, then consider the technical implications.
    – Q Studio
    Jan 9, 2021 at 13:33
  • 1
    @QStudio It was a nonce issue
    – user145078
    Jan 9, 2021 at 14:07

1 Answer 1

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();
    });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy