2

I have a woocommerce site and I want its REST API to be open to the world.

I have learned that CORS headers need to be set, so I google and setup the following hook:

add_action('rest_api_init', function() {
remove_filter('rest_pre_serve_request', 'rest_send_cors_headers');   
add_filter('rest_pre_serve_request', function( $value ) {
    header( 'Access-Control-Allow-Origin: *' );
    header( 'Access-Control-Allow-Methods: OPTIONS, GET, POST, PUT, PATCH, DELETE' );
    header( 'Access-Control-Allow-Credentials: true' );
    header('Access-Control-Allow-Headers: Authorization,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Origin,Content-Type,X-Auth-Token,Content-Range,Range');
    return $value;
});
}, 15);

I confirmed that my server is responding with the correct CORS headers:

Access-Control-Allow-Credentials: true

Access-Control-Allow-Headers:

Authorization,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Origin,Content-Type,X-Auth-Token,Content-Range,Range

Access-Control-Allow-Methods: OPTIONS, GET, POST, PUT, PATCH, DELETE

Access-Control-Allow-Origin: *

Access-Control-Expose-Headers: X-WP-Total, X-WP-TotalPages

Then I headed to code the client side:

xhr = new XMLHttpRequest();
xhr.open('POST', 'https://..../wp-json/wc/v3/products');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.setRequestHeader('Authorization', 'Basic ' + btoa('mykey:mysecret'));
xhr.send(JSON.stirngify({ ... });

Above code was entered in Chrome console under a https://google.com tab. I just can't get the preflight request to work, here are the errors:

OPTIONS https://..../wp-json/wc/v3/products 401 (Unauthorized)

Access to XMLHttpRequest at 'https://..../wp-json/wc/v3/products' from origin 'https://www.google.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

Even though the response headers are exactly like posted above.

What am I doing wrong?

Constantin Groß
  • 10,719
  • 4
  • 24
  • 50
Shawn
  • 32,509
  • 17
  • 45
  • 74
  • 2
    See the answer at https://stackoverflow.com/a/44884623/441757. You need to add handling for OPTIONS requests, and that answer explains how to add that handling in your Apache config. I think it might be necessary to do it there — in the Apache config — rather than in your woocommerce/wordpress/php code – sideshowbarker Oct 16 '19 at 07:26

1 Answers1

0

if you are using: "Access-Control-Allow-Credentials" = true make sure that "Access-Control-Allow-Origin" is not "*", it must be set with a proper domain!