Most up to date post is here: https://robertmarshall.dev/blog/wordpress-rest-api-cors-issues
Are you using WordPress as a headless CMS? Are you trying to work with REST API, but be as secure as possible? Are you getting the following CORS header errors:
“Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.”
“X has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: It does not have HTTP ok status.”
I found this as well! Mainly due to WordPress not the simplest thing to use when dealing with the REST API and CORS security.
The solution is this:
<?php add_action('init', 'handle_preflight');
function handle_preflight() {
$origin = get_http_origin();
if ($origin === 'https://yourfrontenddomain') {
header("Access-Control-Allow-Origin: " . HEADLESS_FRONTEND_URL);
header("Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE");
header("Access-Control-Allow-Credentials: true");
header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization');
if ('OPTIONS' == $_SERVER['REQUEST_METHOD']) {
status_header(200);
exit();
}
}
}
add_filter('rest_authentication_errors', 'rest_filter_incoming_connections');
function rest_filter_incoming_connections($errors) {
$request_server = $_SERVER['REMOTE_ADDR'];
$origin = get_http_origin();
if ($origin !== 'https://yourfrontenddomain') return new WP_Error('forbidden_access', $origin, array(
'status' => 403
));
return $errors;
}
?>
Hope it helps!
Top comments (8)
still facing issue 😞 using localhost, wasted a day help me.
Did you add localhost to your function? Either localhost or localhost
hey, i solved my error by changing my shared hosting service, i was using free service of infinityfree but then i changed to 000webhostapp its working fine.
Legend mate thank you.
I was caught up trying to send header authentication from ReactJS to WooCommerce REST API via fetch() - nearly did it, but this finally got me there.
Glad this helped! :)
Thanks'! This is a day-saving article for me!
i should put this code on my wp-content/themes/twentytwentyone/functions.php and under if ( ! function_exists( 'twenty_twenty_one_setup' ) ) ?
anyone got github folder i can check out ?