WP Rest API V2 CORS错误预检响应

时间:2016-11-15 19:06:56

标签: php angularjs wordpress rest

我正在尝试使用WordPress管理的AngularJS开发一个网络应用程序。我已经安装了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/')
                }
            }

        }

})();

因此,当我访问我的网站并尝试在我的localhost上记录结果时,我收到此错误:

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.

2 个答案:

答案 0 :(得分:0)

我建议您允许所有跨域请求到您的WordPress站点的REST API。我为此写了plugin

答案 1 :(得分:0)

根据“Ahmad Awais”:

// 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;
    });
}