Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enable CORS on JSON API Wordpress

I have this wordpress site with a plugin called JSON API. This plugin provides a JSON format for the content that is in the wordpress. I was able to enable CORS on the wordpress by adding header("Access-Control-Allow-Origin: *"); on the php header. But when I tried the url that the JSON API plugin provides the CORS does not work anymore.

This is the wordpress site were I'm doing the tests... I used the test cors website to check if it was working and it is... http://kiwa-app.loading.net/

But when I try with the url that the JSON api provides me, is not working anymore. I'm still have the error No 'Access-Control-Allow-Origin' http://kiwa-app.loading.net/?json=info

I will apreciate some help thanks!!!

like image 436
Mario Sanchez Maselli Avatar asked Sep 06 '14 16:09

Mario Sanchez Maselli


People also ask

How do I enable CORS on my WordPress REST API?

I was able to enable CORS on the wordpress by adding header("Access-Control-Allow-Origin: *"); on the php header.

How do I resolve CORS issue in WordPress?

If your site loads JavaScript files from a different subdomain, then your CDN needs to provide this Access-Control-Allow-Origin response header for all these assets. Access-Control-Allow-Origin: https://www.yourdomain.com or the less restrictive Access-Control-Allow-Origin: * should work.

Does CORS apply to APIs?

The CORS mechanism supports secure cross-origin requests and data transfers between browsers and servers. Modern browsers use CORS in APIs such as XMLHttpRequest or Fetch to mitigate the risks of cross-origin HTTP requests.


2 Answers

I've used a few different WordPress API's - but for those of you using the 'official' WP-API, I had much trouble with this CORS --- and what I found was that between the .htaccess approach and a few others I stumbled upon... adding this to your theme functions.php worked best.

function add_cors_http_header(){     header("Access-Control-Allow-Origin: *"); } add_action('init','add_cors_http_header'); 

Be sure not to use any combinations of these ( .htaccess, header.php, api.php, functions.php ) as it will be angry at you.

like image 80
sheriffderek Avatar answered Oct 27 '22 05:10

sheriffderek


Ok I finally figured out an easy way...

You just have to add:

     <? header("Access-Control-Allow-Origin: *"); ?> 

On the file api.php, this file is located in wp-content/plugins/json-api/singletons/api.php

I hope it helps more people with the same problem!

like image 39
Mario Sanchez Maselli Avatar answered Oct 27 '22 06:10

Mario Sanchez Maselli