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>
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().