CORS in a WP API plugin

enter image description here

I’m trying to debug the JWT plugin for the WordPress API. I’m using it with Angular CLI and the dev environment runs on localhost:4200 while WP is on localhost. I am way out of my depth here, but absolutely unable to test my code because of these errors. (Note that I know the routes basically work as I can reach them using Postman.)

The author runs

private function define_public_hooks()
    $plugin_public = new Jwt_Auth_Public($this->get_plugin_name(), $this->get_version());
    $this->loader->add_action('rest_api_init', $plugin_public, 'add_api_routes');
    $this->loader->add_filter('rest_api_init', $plugin_public, 'add_cors_support');

Then we have

public function add_cors_support()
    $enable_cors = defined('JWT_AUTH_CORS_ENABLE') ? JWT_AUTH_CORS_ENABLE : false;
    if ($enable_cors) {
        $headers = apply_filters('jwt_auth_cors_allow_headers', 'Access-Control-Allow-Headers, Content-Type, Authorization');
        header(sprintf('Access-Control-Allow-Headers: %s', $headers));
        header('Access-Control-Allow-Headers: Access-Control-Allow-Headers, Content-Type, Authorization');

I see the error_log in my logs, and have tried all sorts of ideas from the web to set headers with various other values. I also had (but commented out) CORS permissions in .htaccess.

But in the dev console I get

XMLHttpRequest cannot load http://localhost/wp-json/restos/v1/post/. Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.


Read more here: CORS in a WP API plugin

Leave a Reply

Your email address will not be published. Required fields are marked *