skip to Main Content

I’ve been struggling with this error after migrating a site from Google Cloud in which I was using Nginx and now I changed the hosting to an Apache server.

The website is in 2 sections front-end (hosted on Vercel NextJS) and the backend which is a WordPress site used as an API with GraphQL (this is the one I migrated) I have used the GraphQL plugin and now the request from the front-end is getting this error:

Access to XMLHttpRequest at [backend domain] from origin [front end domain] has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

I have added this to the .htaccess file:

Header add Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Methods "GET,PUT,POST,DELETE"
Header set Access-Control-Allow-Headers "Content-Type"

I’m using Cloudflare in both the backend and the frontend.

Don’t know what else to do. I have tried to go back to the previous hosting and it works perfectly so I don’t know what’s the problem! Please help! Thank you! 🙂

3

Answers


  1. Chosen as BEST ANSWER

    It's fixed! Apparently, I had to flush the permalinks by just saving the permalinks settings: Settings > Permalinks

    I found the solution here: https://github.com/wp-graphql/wp-graphql/issues/213


  2. Add this filter in functions.php file in theme and make sure SSL enabled

        add_filter('rest_pre_serve_request', 'cors_headersxxxx', 0, 4 );
        function cors_headersxxxx() {
          header( 'Access-Control-Allow-Origin: *');
          header( 'Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE' );
          header( 'Access-Control-Allow-Credentials: true' );
          header( 'Access-Control-Allow-Headers: Authorization, Content-Type, X-Requested-With, X-Mystore-Cartkey, X-USER-ID' );
          //header( 'Access-Control-Expose-Headers: X-Mystore-Cartkey' );
        }
    
    
        add_filter('rest_api_init', 'wp_mystore_jwt_add_cors_support');
        function wp_mystore_jwt_add_cors_support() {
          $enable_cors = true;
          if ($enable_cors) {
            $headers = 'Access-Control-Allow-Headers, X-Requested-With, Content-Type, Accept, Origin, Authorization';
            header( sprintf( 'Access-Control-Allow-Headers: %s', $headers ) );
          }
        }
    
    Login or Signup to reply.
  3. This is not really safety but it works for me

    I’ve put this to .htaccess file

    Header set Access-Control-Allow-Origin '*'
    Header set Access-Control-Allow-Headers '*'
    Header set Access-Control-Allow-Methods '*'
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search