最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Solve cors problem using rest api or ajax

programmeradmin1浏览0评论

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 = `/${homeUrls[locale]}`;

const servicesUrl = `;lang=${locale}`;

const projectsUrls = {
  es: '23',
  en: '40',
};
const projectsUrl = `/${projectsUrls[locale]}`;
const projectListUrl = `;lang=${locale}`;

const clientListUrl = `;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:

Network:

Console:

And don't provide response so my app crashes:

发布评论

评论列表(0)

  1. 暂无评论