Solving Rest API CORS Issues in WordPress as a Headless CMS

Solving Rest API CORS Issues in WordPress as a Headless CMS

Solving Rest API CORS Issues in WordPress as a Headless CMS

If you are using WordPress as a Headless Cms then you must be faced these find of header errors like

  • “Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.”
  • “X has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: It does not have HTTP ok status.”
  • “Request header field x-wp-nonce is not allowed by Access-Control-Allow-Headers in preflight response.”

So, when you faced this kind of problem you need to add this solution in your theme function.php . Here is the Solution For this header error

function add_custom_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;
    } );
}
add_action( 'rest_api_init', 'add_custom_headers', 15 );


Hopefully this solves your WordPress CORS issue!

WordPress REST API CORS Issues Solved

Read More: 4 Step to Create a WordPress Child Theme, WordPress walker_nav_menu: Basic Usage of walker_nav_menu, 5 Steps to Enhance WordPress Search with Autocomplete and AJAX, Easy Floating Share Button – Social Share WordPress Plugin, How to Create WordPress Plugin from Scratch – Step-by-Step Guide

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top
Theme Mode