3

I tried to get data from wordpress rest api from a js application which is in a cross domain, I got Access-Control-Allow-Origin error

axios.get(`https://bikeguy.xyz/wp-json/wp/v2/posts?categories=86`)
   .then( posts => console.log(posts) )
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

enter image description here

To allow cross domain access, I put these codes in functions.php file , but I get still same errors

// Hook.
add_action( 'rest_api_init', 'wp_rest_allow_all_cors', 15 );
/**
 * Allow all CORS.
 *
 * @since 1.0.0
 */
function wp_rest_allow_all_cors() {
    // Remove the default filter.
    remove_filter( 'rest_pre_serve_request', 'rest_send_cors_headers' );
    // Add a Custom filter.
    add_filter( 'rest_pre_serve_request', function( $value ) {
        header( 'Access-Control-Allow-Origin: *' );
        header( 'Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE' );
        header( 'Access-Control-Allow-Credentials: true' );
        return $value;
    });
} // End fucntion wp_rest_allow_all_cors().
King Rayhan
  • 2,287
  • 3
  • 19
  • 23

1 Answers1

0

I would like to add one more filter to prevent this.

Danger! Don't use in the production or without condition.

add_filter( 'rest_authentication_errors' , function() {
   wp_set_current_user( 1 );
}, 101 );

or full function:

function wp_api_allow_cors() {
  remove_filter( 'rest_pre_serve_request', 'rest_send_cors_headers' );
  add_filter( 'rest_pre_serve_request' , function( $value ) {
    header( 'Access-Control-Allow-Headers: Authorization, X-WP-Nonce,Content-Type, X-Requested-With');
    header( 'Access-Control-Allow-Origin: *' );
    header( 'Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE' );
    header( 'Access-Control-Allow-Credentials: true' );
    return $value;
  });

  // Danger: Don't use in the production or without condition.
  $domains = array( 'localhost', 'mydomain.com' );
  if ( in_array( $_SERVER['SERVER_NAME'], $domains ) ) {
    add_filter( 'rest_authentication_errors' , function() {
      wp_set_current_user( 1 );
    }, 101 );
  }
}

add_action( 'rest_api_init', 'wp_api_allow_cors', 15 );
l2aelba
  • 21,591
  • 22
  • 102
  • 138