I'm trying to develop a web app with AngularJS that's managed with WordPress. I've installed WP and the WP Rest API V2 plugin. I want to get my response with Angular's $http and work with the returned data.
I have my factory that looks like this:
(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/')
}
}
}
})();
So when I visit my site and try to log the results on my localhost I get this error:
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.
I'd recommend you to Allow all cross-origin requests to your WordPress site's REST API. I wrote a plugin for just that.
according to "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;
});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.