CORS wierd problem

Hi again :slight_smile:

I hope this time any one can answers me :sweat_smile:

I recorded this --> video <-- to explain my problem.

when I navigates from link to another sometimes CORS error fires and prevent fetching of this page

image

I tried many options to enable the CORS as https://github.com/ahmadawais/WP-REST-Allow-All-CORS plugin

OR

adding code in functions.php file

// Hook.
add_action( 'rest_api_init', 'wp_rest_allow_all_cors', 15 );
/**
* Allow all CORS.
*/
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-Headers: *' );
        header( 'Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE' );
        header( 'Access-Control-Allow-Credentials: true' );
        return $value;
    });
}

But without any help.

PLEASE help me guys.

Hi @modyydom

  1. Could you post the code in your component that you are having problems with?

  2. Are you sure that the links are redirecting to the correct URL? In your video I noticed in the console that the data has a value of {is404: true} when you click on one of the hyperlinks. It would also be helpful if you could rerecord the screencast with the URL visible in the browser.

  3. I see that you are making the request from localhost to a remote server (which I assume is your production or staging environment). Could you confirm for me that the changes that you’ve been making to your backend (e.g in the .php file) are actually being deployed to that environment?

It’s hard to tell what’s wrong without knowing what’s going on in your WP but here are some ideas:

Check the headers of those responses to see if CORS headers are present. As an example, when requesting https://test.frontity.io/wp-json/wp/v2/pages?_embed=true&slug=about-us these are the headers I get:


I think this is the default behavior.

If those headers are not present then the code you added to functions.php isn’t working. Why? I’d guess something is overriding those headers.

Try to see what filters are making use of that same hook in case one of them comes after yours and changes that. I simple test would be to add to your functions.php something like this:

add_action( 'rest_api_init', function() {
    global $wp_filter;
    var_dump($wp_filter['rest_pre_serve_request']);
}, 99 );

This will print on the response’s body something like:

object(WP_Hook)#251 (5) {
  ["callbacks"]=>
  array(1) {
    [10]=>
    array(2) {
      ["_oembed_rest_pre_serve_request"]=>
      array(2) {
        ["function"]=>
        string(30) "_oembed_rest_pre_serve_request"
        ["accepted_args"]=>
        int(4)
      }
      ["rest_send_cors_headers"]=>
      array(2) {
        ["function"]=>
        string(22) "rest_send_cors_headers"
        ["accepted_args"]=>
        int(1)
      }
    }
  }
  ["iterations":"WP_Hook":private]=>
  array(0) {
  }
  ["current_priority":"WP_Hook":private]=>
  array(0) {
  }
  ["nesting_level":"WP_Hook":private]=>
  int(0)
  ["doing_action":"WP_Hook":private]=>
  bool(false)
}

Where you can see the callbacks registered to act on that hook.
If everything looks fine there the overriding might be happening somewhere else.

You can also try to hook your code in functions.php to rest_pre_echo_response which I think is the last hook before the response is sent:

add_action('rest_api_init', 'my_prefix_wp_rest_allow_all_cors');

function my_prefix_wp_rest_allow_all_cors() {
    add_filter( 'rest_pre_echo_response', function( $value ) {
        header( 'Access-Control-Allow-Origin: *' );
        header( 'Access-Control-Allow-Headers: *' );
        header( 'Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE' );
        header( 'Access-Control-Allow-Credentials: true' );
        return $value;
    });
}

Hope anything of this helps.

3 Likes

YOU ARE THE BEST

thank you very muck @orballo

:ok_hand: :+1: :muscle: :heart:

1 Like

Sorry for that @orballo

but the error appears again

this time I noticed something weird

the rejected request is missing many headers

valid request :

invalid request:

I don’t know if this has any significance ??

Do the posts and pages from before work now? Or is it still the same error?

If not, what are you trying to call? Can you post here the failing request?

if you are on page http://localhost:3000/ and then clicked on a link with href="/about-us/" the error appears

the request is
http://wp-local.com/wp-json/wp/v2/pages/?_embed=true&slug=about-us

I run into a similar problem and I realised it was because I was working on localhost, maybe it’s your case too. I guess your web is only able to show the pages and posts that have been fetched from the server. The ones you try to fetch from localhost return that error.

In order to “solve” it I installed this Chrome extension, moesif, and turned it to on. It doesn’t solve the problem but it lets you see the whole web from local. Once you deploy your app to a real domain, the CORS problems should be solved. You could test it by deploying it to a different domain than the real one (like the one Zeit Now gives you by default, mysite.now.sh).

This guy here explains it much better.

Not sure if it’s your case, let us know if you find it helpful.

This is really a very frustrating error.

thanks guys for all this support :star_struck:

It looks like the path of the failing request is not /pages but /. And for what I know the only calls that should be done are to /posts and /pages, so it looks like you are doing an extra request for some reason that is failing.

Can you post the code where you are doing this fetchs? Is it in a Link component? Are you doing it manually from somewhere else? Did you wrote any custom handler on your Frontity project that might be interfering?

EDIT: I see you marked @SantosGuillamot response as solution. Is it working now?