XMLHttpRequest 401 (Unauthorized)

I am trying to Create Post in user interface.
When I logged in as Admin and insert

createPost.setRequestHeader("X-WP-Nonce", magicalData.nonce);

to the below code, Create Post success. But I don’t want to use nonce, I want use user and password, but I got this error: 401 (Unauthorized). I tried to replace btoa to Decode64 but it not work. Do I miss anything?

var createPost = new XMLHttpRequest();

createPost.open("POST", magicalData.siteURL + "/wp-json/wp/v2/posts", true);
createPost.withCredentials = true;
createPost.setRequestHeader("Authorization", "Basic " + btoa("username:password"));

createPost.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
createPost.onreadystatechange = function() {
  if (createPost.readyState == 4) {
    if (createPost.status == 201) {
      document.querySelector('.admin-quick-add [name="title"]').value = '';
      document.querySelector('.admin-quick-add [name="content"]').value = '';
    } else {
      alert("Error - try again.");

Read more here: XMLHttpRequest 401 (Unauthorized)

Leave a Reply

Your email address will not be published. Required fields are marked *