Wordpress REST API is sending HTML having script instead of JSON

Viewed 76

I am sending request to WordPress REST API endpoint - https://example.com/wp-json/wp/v2/comments.

But it is not sending JSON as response. Instead, it is sending HTML having script tag as follows -

<html>
  <body>
    <script>
      document.cookie =
        "_test=<cookie value> ; expires=<expiary date>; path=/";
      document.location.href =
        "https://example.com/wp-json/wp/v2/comments";
    </script>
  </body>
</html>

Here, 1) a cookie named _test is getting created, 2) After that, it is redirecting to the requested URL with document.location.href.

So, when I am trying to parse the response using JSON.parse method, then it is failing, as it is in HTML format. But, when I am entering the endpoint URL in browser search bar, then document.location.href method inside the script of the response is helping to redirect to the expected JSON.

My expected response should be like this

[{"id":1,"post":1,"parent":0,"author":0,"author_name":"A WordPress Commenter","author_url":"https:\/\/wordpress.org\/","date":"2022-07-22T16:38:55","date_gmt":"2022-07-22T16:38:55","content":{"rendered":"Comment 1"}}, /*...*/]

Now, how to get response as JSON directly, instead of HTML?

1 Answers

Your question is confusing. In your code you are using JavaScript to redirect the page to the json data, not fetch the information.

Try this and check your console. You should be able to take it from there.

const url = "https://example.com/wp-json/wp/v2/comments";
const comments = getComments( url );

// My function
async function getComments( url ) {
    // Try to fetch the url
    await fetch( url )
        .then( function ( response ) {
        console.log( response );

        // Get the status
        console.log( "Status code: " + response.status );

        // The API call was unsuccessful
        if ( response.status > 299 ) {
            throw new Error( finalError );

        // The API call was successful
        } else {
            return response.json();
        }
        })
        .then( function ( data ) {
        // This is the response data as a text string
        console.log( data );

        // Make sure we have data
        if ( data.length == 0 ) {
            throw new Error( finalError );
        }

        // Only continue if not null or empty
        if ( data[0] !== null && data[0] !== undefined && data.length > 0 ) {

            // Iter through each item
            for ( let d = 0; d < data.length; d++ ) {
            
                // Log it
                console.log( data[d] );
            }
        }
        })
        .catch( function handleError( error ) {
            console.log( error );
        }
    );
}
Related