rest api – WordPress plugin with CORS


I have couple API routes that I want to use on another site by making ajax calls, however, I keep getting Cross-Origin Read Blocking (CORB) blocked cross-origin response.

I have tried CORS PLUGINS setting it to wildcard (*), also have tried numorous answers in this and other communities to no avail.

add_action( 'init', 'allow_origin' );
function allow_origin() {
    header("Access-Control-Allow-Origin: *");

also tired this

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

Please note, I’m getting this error on local environment provided by local by flywheel. Perhaps there is a server setting I have to tweak but I wasn’t able to google it out.

Also, this is my ajax function

  url: url,
  contentType: "application/json",
  dataType: "jsonp",
  success: function(result){
    let data = $.parseJSON(result);
    if (data.status === "success"){
    }else if (data.status === "error"){

And this is how routes are registered

add_action( 'rest_api_init', function () {
    register_rest_route( 'rc-design-issue/v1', '/new-previews/', array(
      'methods' => 'GET',
      'callback' => 'generate_new_previews',
    ) );

    register_rest_route( 'rc-design-issue/v1', '/new-proofs/', array(
        'methods' => 'GET',
        'callback' => 'generate_new_proofs',
      ) );
} );

This all works great on the same domain, but when I put this plugin onto a different domain(locally) I get CORS error.

ivan marchenko 4 months 2022-04-15T13:00:27-05:00 0 Answers 0 views 0

Leave an answer