Welcome Guest, Not a member yet? Register   Sign In
CORS policy on single URL
#1

Hi All,
I got a rest API setup using CI4 but when I try to hit the API using Ajax out side of the domain I get a CORS policy error. Is there a way to allow cross domain access just to one API/URL. Everything works perfect via Postman/curl.
Below is the error I get on the console (when using plain JS).


Access to XMLHttpRequest at 'xxx/api/app_rating/add' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Reply
#2

hi @chakycool ,
You can create a filter and in the "before" function of the filter. You can add below code:

$response = Services::response();
$response->setHeader("Access-Control-Allow-Origin", "*")
->setHeader("Access-Control-Allow-Headers", "X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method")
->setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, DELETE");

Then in routes.php, add this filter to you the url you want to use for AJAX.

If you are writing only REST APIs, then you can use agungsugiarto/codeigniter4-cors package as well. That way you can set CORS for all urls. As you request for only one URL then you can use above code in custom filter.

Hope this helps.
Reply
#3

Do not ever use the * in a CORS string on a live site anyone could access it!
Use the full url ( https://www.mysite.com ).
What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )
Reply
#4
Thumbs Up 
(This post was last modified: 12-08-2022, 02:10 AM by chakycool.)

(12-07-2022, 08:03 AM)encodedigital Wrote: hi @chakycool ,
You can create a filter and in  the "before" function of the filter. You can add below code:

$response = Services::response();
$response->setHeader("Access-Control-Allow-Origin", "*")
      ->setHeader("Access-Control-Allow-Headers", "X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method")
      ->setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, DELETE");

Then in routes.php, add this filter to you the url you want to use for AJAX.

If you are writing only REST APIs, then you can use agungsugiarto/codeigniter4-cors package as well. That way you can set CORS for all urls. As you request for only one URL  then you can use above code in custom filter.

Hope this helps.

Amazing encodedigital..The filter worked. Will check out the package as well but I needed open just for 1 API/URL.
Thank you so much.

(12-08-2022, 12:32 AM)InsiteFX Wrote: Do not ever use the * in a CORS string on a live site anyone could access it!
Use the full url ( https://www.mysite.com ).

Thanks for the heads up Smile
Reply




Theme © iAndrew 2016 - Forum software by © MyBB