score:2

First of all i would like to point out that your Get requests work because they belong to the category which does not trigger a preflight request. While your Post request is probably using some header which removes it from the category hence requiring preflight to pass. If you are interested in reading more, here is the documentation link.

https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Simple_requests

Now, according to your comment, the error you are getting is

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

The method you are using for setting headers, as you mentioned in a comment, does not work on rest requests. You can use below function in your functions.php or a plugin file to set the origin to *.

function sr_rest_send_cors_headers( $value ) 
{   
    header( 'Access-Control-Allow-Origin: *' );
    header( 'Access-Control-Allow-Methods: OPTIONS, GET, POST, PUT, PATCH, DELETE' );
    header( 'Access-Control-Allow-Credentials: true' );
    header( 'Vary: Origin', false );

    return $value;
}
add_filter( 'rest_pre_serve_request', 'sr_rest_send_cors_headers', 11 );

Although i recommend what WordPress does by default. If you check wp-includes/rest-api.php you will find the original function which i have modified for your purpose. If you are interested in taking a look, here is the trac link.

https://core.trac.wordpress.org/browser/tags/5.4/src/wp-includes/rest-api.php#L574


Related Query

More Query from same tag