Understanding the Access-Control-Allow-Headers in preflight response for Wordpress and VueJS

Attempting to retrieve a route from candriam-app.nanosite.tech to candriam.nanosite.tech has proven challenging. Despite various attempts to allow headers, I continue to encounter this CORS 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.

The goal is to create a headless Wordpress site for xxxA. Requests to the WP Rest API work smoothly from candriam-app.nanosite.tech, but issues arise when interacting with an endpoint created by the extension found here: https://github.com/haet/ninja-forms-submissions-rest-endpoint

Following the documentation, the request code looks 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 matches the one provided by the module.

Various server-side methods have been attempted:

In functions.php, the following code was tested :

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, this approach was tried :


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

Additionally, these combinations were also experimented with :

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

Despite these efforts, the error persists.

Could it be due to a bug in the plugin? Is there a specific permission needed for this plugin or header (nf-rest-key) on the server side?

When inspecting the server headers (such as using a service like this: ), should authorization for the website where my app is hosted be visible?

Answer №1

To solve the issue at hand, I successfully implemented the following code snippet within functions.php :

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

    $origin = get_http_origin();
    if ($origin == 'http://localhost:8080' ||    $origin == 'https://xxxxxB') {
        // Additional domains can be specified as needed
        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();
        }
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing Bootstrap's hidden command to pinpoint specific titles

Here is the code I have that generates previous and next links for my Wordpress post. I am looking to hide the title of these links and instead display 'back' and 'next' as the text. The current code successfully hides the icon display ...

What sets v-html apart from v-text?

I recently encountered this issue with the v-text directive: <h1 v-text="content.title"></h1> Result was: Brand Name is B&amp;C To resolve it, I switched to using the v-html directive in the line above: <h1 v-html="con ...

I can view the data retrieved in the console, but I am having difficulty displaying it on the screen

I have successfully retrieved data from the API, as indicated by the output in my console. However, I am facing issues in displaying this data on the webpage due to a potential error in my code structure. Despite this, I can confirm that the fetched data ...

Guide to activating vue lazy loading for applications served from a Content Delivery Network (CDN)

I've recently embarked on a project that involves separating the frontend and backend components. The backend, powered by Laravel, serves APIs while the frontend, built with VueJS, consumes those APIs. My approach includes deploying the Laravel app o ...

What is the best way to incorporate a button for toggling CSS animations?

I need help adding a button to toggle the animation on this JSFiddle. I tried adding the code below but can't seem to start and stop the animation. body .a [class^="b"] { width: 200px; height: 142.8571428571px; margin: 0 auto; ...

Need help setting parsed values on jQuery Autocomplete after Keyup event?

I am using the Bing API to retrieve values by accessing this link: When I parse and append the results on keyup, it works fine. However, when I try to set the results on jQuery's autocomplete, it does not display properly. For example, you can view ...

What is the process for selecting the Node version when installing with .nvm?

I am having an issue with nvm in the terminal. When I try to run npm install <something>, it always installs the package in node version 9.4.0, regardless of the version set using nvm. Even after switching to node version 10.15.3 using nvm use v10.1 ...

Having trouble retrieving state values from the store in Vue3

The data sent from index.vue to user.js is saved in the Array users. I confirmed that users received the data from index.vue using localstorage. I then attempted to access the Array users in chat.vue from users.js Unfortunately, I am experiencing issues w ...

Is it advisable to create a component for each codebase when combining multiple codebases into one?

Embarking on a new project where the goal is to merge 7 different codebases into a single cohesive one. Each individual codebase serves a unique purpose, such as Registration, Surveys, Email Blaster, and more. My plan is to utilize Vue for the frontend and ...

The CORS policy is preventing the AJAX request from functioning properly on localhost

Recently, I have been working on an Angular application that requires interaction with an API. To test it out, I set up an API on my localhost and made a request using AJAX. However, I encountered the dreaded CORS error. Despite trying various solutions fo ...

I'm looking to add a price ticker to my html webpage. Does anyone know how to do this?

PHP Code <?php $url = "https://www.bitstamp.net/api/ticker/"; $fgc = file_get_contents($url); $json = json_decode($fgc, true); $price = $json["last"]; $high = $json["high"]; $low = $json["low"]; $date = date("m-d-Y - h:i:sa"); $open = $json["open"]; ...

What strategies would you use to put in place conditional imports in a way that is reminiscent of ReactNative

Is there a way to implement conditional imports in other projects similar to how React Native imports Android or iOS specific classes using *.android.js and *.ios.js? If I wanted to have different classes for development and production purposes, could I u ...

Unexpected behavior when using Async.map in conjunction with async.waterfall

Utilizing Async, I am using async.map() to connect my data array with a function and incorporating async.waterfall() within that function to execute functions in a series. However, the waterfall function is not functioning as anticipated. I have also attem ...

Exploring the attributes of cycled values in Vue.js

Currently, I am iterating over a list as shown below: <li v-for="item in filteredParentItems" v-if="item.action === 'list'" v-on:click="getNextPath" v-bind:data-next-path="item.nextPath" v-bind:data-action="item.action ...

What is the best way to notify the JSON code below using jQuery?

I have received a JSON response after using the Reverse Geocoding API from Google. The response includes various address components such as route, sublocality, locality, and political information. { "results": [ { "address_components": [ ...

What are the steps for utilizing JSON data retrieved from an ajax response?

After successfully making an ajax request and receiving JSON data, I am struggling with how to use it effectively. The response I am getting looks like this: [{ "id": "5", "reviewID": "2389", "serviceID": "50707", "title": "well d ...

"An error occurs when attempting to clear Rad Grid data with javascript: htmlfile: Invalid argument thrown

Hello, I am currently developing an ASP.NET application. I am facing an issue where I need to clear the data in a Rad grid upon button click using JavaScript. The code snippet that I have attempted for this is as follows: document.getElementById(&a ...

Is it possible to create a compound editor within a cell in SlickGrid that contains two date fields

Currently, I am implementing SlickGrid with jQuery and I am interested in incorporating a compound editor within a cell similar to example 3a mentioned here. However, instead of two text fields, I would like to have two date fields. Although Example 3 dem ...

Is it possible to trigger the @click event in Vuejs when utilizing v-html to render HTML content?

Here is an interesting HTML scenario: errorText: '<a class="button" @click.prevent="enableExceedable(issue.mapping)">Enable exceedable limits</a>'; I am trying to insert this string into the following div: <div v-if="hasIssue != ...

Error in Nestjs Swagger: UnhandledPromiseRejectionWarning - The property `prototype` cannot be destructed from an 'undefined' or 'null' object

Currently, I am in the process of developing a Nestjs REST API project and need to integrate swagger. For reference, I followed this repository: https://github.com/nestjs/nest/tree/master/sample/11-swagger However, during the setup, I encountered the foll ...