Reputation: 13
I've created a WP rest API that works with ionic app. Does work on my localhost, but when I run the app in a iphone simulator, It does not work. The WP REST API does not display the content anymore.
What could be the problem?
Upvotes: 1
Views: 272
Reputation: 681
WordPress by default control the protocols that are allowed to access the framework (http://...., ftp://.....) for security means (https://tommcfarlin.com/what-is-wordpress-kses/).
When running an ionic app on device in debugging or production mode, it specifies the origin of the requests as ionic://localhost. Then, you have to tell the WP to accept requests from this origin.
Place this code in your theme's functions.php as it will fix the problem with iOS HTTP requests to the WP REST API:
// Adding ionic Protocol Start.
add_filter('kses_allowed_protocols', function ($protocols) {
$protocols[] = 'ionic';
return $protocols;
});
// Adding ionic Protocol End.
By the way, if you face CORS errors at any time, make sure to place this code also in the functions.php:
// Enabling CORS Start.
function handle_preflight()
{
$origin = get_http_origin();
header("Access-Control-Allow-Origin: " . $origin);
// Specify the allowed HTTP methods.
header("Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE");
header("Access-Control-Allow-Credentials: true");
header('Access-Control-Allow-Headers: Authorization, Content-Type');
if ('OPTIONS' == $_SERVER['REQUEST_METHOD']) {
status_header(200);
exit();
}
}
add_action('init', 'handle_preflight');
function add_cors_http_header()
{
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
}
add_action('init', 'add_cors_http_header');
// Enabling CORS End.
Upvotes: 1