Solve cors problem using rest api or ajax

by Toni Michel Caubet   Last Updated October 17, 2019 11:08 AM

I'm building an app with nuxt using WP as a CMS, so I have this code in my functions.php to allow any origin (temporary) using the rest api and admin-ajax urls

function add_cors_http_header(){
    // Remove the default filter.
    remove_filter( 'rest_pre_serve_request', 'rest_send_cors_headers' );
    // Add a Custom filter.
    add_filter( 'rest_pre_serve_request', function( $value ) {
        header( 'Access-Control-Allow-Origin: *' );
        header( 'Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE' );
        header( 'Access-Control-Allow-Credentials: true' );
        return $value;
    });
}
add_action( 'init', 'add_cors_http_header', 99 );
add_action( 'rest_api_init', 'add_cors_http_header', 99 );

The requests that i'm using are:

const homeUrl = `http://our-webiste.com/wp-json/wp/v2/pages/${homeUrls[locale]}`;

const servicesUrl = `http://our-webiste.com/wp-json/wp/v2/service?_embed=true&lang=${locale}`;

const projectsUrls = {
  es: '23',
  en: '40',
};
const projectsUrl = `http://our-webiste.com/wp-json/wp/v2/pages/${projectsUrls[locale]}`;
const projectListUrl = `http://our-webiste.com/wp-json/wp/v2/project?_embed&lang=${locale}`;

const clientListUrl = `http://our-webiste.com/wp-json/wp/v2/client?_embed&lang=${locale}`;

/* Requests */
let home = await axios.get(homeUrl);

let services = await axios.get(servicesUrl);

let projectsPage = await axios.get(projectsUrl);
let projectsList = await axios.get(projectListUrl);

let clientsList = await axios.get(clientListUrl);

that most of the times work with no problem but some times they return this:

enter image description here

And don't provide response so my app crashes:

enter image description here



Related Questions


accessing WordPress DB from remote server

Updated November 23, 2017 16:08 PM