API call does not work

0

I have the following code:

// Jquery Script

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

// JS Script

$.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 can not load link The 'Access-Control-Allow-Origin' header has a value ' link ' that is not equal to the supplied origin. Origin 'null' is therefore not allowed access. "

How to receive the error-free call date and only display the title of the posts?

    
asked by anonymous 20.04.2017 / 22:21

2 answers

0

You probably need to add the Header to CORS on the server side (where json is generated in the url you posted). In C # for example, I use Response.AppendHeader ("Access-Control-Allow-Origin", "*");

    
20.04.2017 / 22:39
0

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

/**
* 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 do not have access, then you need to create a middleware, a server that requests and responds to the request, eg an application in node.js that when you hit a url, your api, get the data and return on the request you are making.

So: get to link - > hit the url link - > responds to the content of this url.

    
21.04.2017 / 21:10