Home > Back-end >  Weird 401 and 403 with wordpress REST API (wp-json)
Weird 401 and 403 with wordpress REST API (wp-json)

Time:01-06

I am getting mad because as a lodded-in wordpress admin, on the front-end (not in the admin portal), I cannot make post/put requests. A simple GET AJAX request works perfectly without any type of credentials:

   axios.get(this.page.url   "/wp-json/wp/v2/posts").then((resp) => {
      console.log(resp.data);
    });

BUT, when I try to make post requests I always get 401 error if I do not include the nonce. If I include the nonce, I get 403. Tried with both AXIOS and JQUERY:




// Axios:
axios.defaults.withCredentials = true;
    axios.defaults.headers.post["X-WP-Nonce"] = MYSCRIPT.nonce; // for POST request

    axios
      .post(this.page.url   "/wp-json/wp/v2/posts", {
        title: "title",
        content: "content",
        status: "publish",
      })
      .then(function (response) {
        console.log(response);
      })
      .catch(function (error) {
        console.log(error);
      });

// JQUERY
$.ajax({
      url: this.page.url   "/wp-json/wp/v2/posts",
      type: "post",
      data: {
        title: "title",
        content: "content",
        status: "publish",
      },
      headers: {
        "X-WP-Nonce": MYSCRIPT.nonce, //If your header name has spaces or any other char not appropriate
      },
      dataType: "json",
      success: function (data) {
        console.info(data);
      },
    });

The nonce is simply generated with:

    <script>
        <?php echo 'const MYSCRIPT = ' . json_encode(
            array('nonce' => wp_create_nonce('wp-rest'))
        ); ?>
    </script>

I know this is not good practice, and I will include it properly as soon as I get it to work. The nonce is perfectly retrieved by Javascript, but I get 403 from wordpress... No idea on how to proceed!

CodePudding user response:

The action specified in wp_create_nonce should be wp_rest (underscore), not wp-rest (hyphen).

https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/

For developers making manual Ajax requests, the nonce will need to be passed with each request. The API uses nonces with the action set to wp_rest

Replace wp-rest with wp_rest and it should work properly.

  • Related