Call in API does not work

Asked

Viewed 260 times

0

I have the following code:

// Script Jquery

<script
  src="https://code.jquery.com/jquery-3.2.1.min.js"
  integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
  crossorigin="anonymous"></script>

// Script JS

$.ajax({
    type: "GET",
    url: "http://revistadesignmagazine.com/wp-json/wp/v2/posts",
    error: function (xhr, ajaxOptions, thrownError) {
      alert(xhr.status);
      alert(thrownError);
    }
}).done(function ( data ) {
  console.log(data);
});

When I make the call I get the following error:

"Xmlhttprequest cannot load http://revistadesignmagazine.com/wp-json/wp/v2/posts. The 'Access-Control-Allow-Origin' header has a value 'http://null' that is not Equal to the supplied origin. Origin 'null' is therefore not allowed access."

How to receive the call date without errors and display only the post title?

2 answers

0

If you have access to wordpress, you can add functions.php within the theme used: (I used this function with the wp-Rest plugin as well)

/**
* Add REST API support to an already registered post type.
*/
/**
 * Use * for origin
 */
add_action( 'rest_api_init', function() {

    remove_filter( 'rest_pre_serve_request', 'rest_send_cors_headers' );
    add_filter( 'rest_pre_serve_request', function( $value ) {
        header( 'Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE' );
        header( 'Access-Control-Allow-Credentials: true' );

        return $value;

    });
}, 15 );

If you don’t have access, then you need to create a middleware, a server that requests and responds to this request data, e.g.: an application in Node.js that when you hit a url, it gets into your api, takes the data and returns in the request you are doing.

So: get to http://seuapp.com/wp-json/wp/v2/posts -> hit the url http://revistadesignmagazine.com/wp-json/wp/v2/posts -> answers the content of this url.

0

You probably need to add the Header to CORS from the server side (where json is generated at the url you posted).

In C# for example, I use Response.AppendHeader("Access-Control-Allow-Origin", "*");

  • There is no way Julio, this is coming from Wordpress

Browser other questions tagged

You are not signed in. Login or sign up in order to post.