簡體   English   中英

WP Rest API V2 CORS 錯誤預檢響應

[英]WP Rest API V2 CORS error preflight response

我正在嘗試使用 AngularJS 開發一個由 WordPress 管理的 Web 應用程序。 我已經安裝了 WP 和 WP Rest API V2 插件。 我想用 Angular 的 $http 得到我的響應並處理返回的數據。

我的工廠看起來像這樣:

(function() {
    'use strict';

    /**
     * @ngdoc function
     * @name app.service:prayersService
     * @description
     * # prayersService
     * Service of the app
     */

    angular
        .module('prayers')
        .factory('PrayersService', Prayers);
        // Inject your dependencies as .$inject = ['$http', 'someSevide'];
        // function Name ($http, someSevide) {...}

        Prayers.$inject = ['$q', '$http'];

        function Prayers ($q, $http) {

            return{
                get: function(){
                    return $http.get('https://drummerboyhosting.com/sandbox/rosary/wp-json/wp/v2/rosary_prayers/')
                }
            }

        }

})();

因此,當我訪問我的網站並嘗試在我的本地主機上記錄結果時,我收到此錯誤:

XMLHttpRequest cannot load https://drummerboyhosting.com/sandbox/rosary/wp-json/wp/v2/rosary_prayers/. Request header field X-Requested-With is not allowed by Access-Control-Allow-Headers in preflight response.

我建議您允許對 WordPress 站點的 REST API 的所有跨域請求。 我為此編寫了一個插件

根據“艾哈邁德·阿瓦伊斯”的說法:

// Hook.
add_action( 'rest_api_init', 'wp_rest_allow_all_cors', 15 );

/**
 * Allow all CORS.
 *
 * @since 1.0.0
 */
function wp_rest_allow_all_cors() {
    // 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' );
        header( 'Access-Control-Allow-Headers: *' );
        return $value;
    });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM