Wordpress and VueJS : Access-Control-Allow-Headers in preflight response

614 views Asked by At

I try to fetch a route from candriam-app.nanosite.tech to candriam.nanosite.tech, I have tried several methods to allow headers but I still have this error

Access to fetch at 'https://xxxA/wp-json/nf-submissions/v1/form/1' from origin 'https://xxxB' has been blocked by CORS policy: Request header field nf-rest-key is not allowed by Access-Control-Allow-Headers in preflight response.

I want to create a headless Wordpress of the website xxxA. I can perform request on the WP Rest API without any problem from candriam-app.nanosite.tech, but I have issues with an endpoint created by this extension : https://github.com/haet/ninja-forms-submissions-rest-endpoint

I followed the documentation and my code to perform the request is like this :

export async function getApiContactForm(route, params = { method: 'get' }) {
  const data = await fetch(route, {
    method: params.method,
    headers: {
      'Content-Type': 'application/json',
      'NF-REST-Key': 'xxxxxxxxxxx',
    },
  })
  const body = data.json()
  return body
}

The NF-Rest-Key is of course the same given by the module.

I have tried different methods on the server-side :

In functions.php, I tried this code :

header( 'Access-Control-Allow-Origin: * ' );
header( 'Access-Control-Allow-Methods: GET' );
header( 'Access-Control-Allow-Credentials: true' );
header( 'Access-Control-Allow-Headers: nf-rest-key' );

In .htaccess file of xxxxxA, I tried this code :


<IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
</IfModule>

I aso tried :

Header set Access-Control-Allow-Origin *
Header set AMP-Access-Control-Allow-Source-Origin *

But I still get the error.

Is it possible that the plugin is bugged ? Do I have to specifically allow this plugin, this header (nf-rest-key) from the server ?

When I check the headers of the server (like here : https://securityheaders.com/) am I supposed to see that the website where my app is stored is authorised ?

1

There are 1 answers

0
Nicolas Troadec On

I resolved my problem by adding this code to functions.php :

add_action('init', 'handle_preflight');
function handle_preflight()
{

    $origin = get_http_origin();
    if ($origin == 'http://localhost:8080' ||    $origin == 'https://xxxxxB') {
        // You can set more specific domains if you need
        header("Access-Control-Allow-Origin: " . $origin);
        header("Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE");
        header("Access-Control-Allow-Credentials: true");
        header('Access-Control-Allow-Headers: NF-REST-Key, Content-Type');

        if ('OPTIONS' == $_SERVER['REQUEST_METHOD']) {
            status_header(200);
            exit();
        }
    }
}