I have created a basic RESTful service with the SLIM PHP framework and now I'm trying to wire it up so that I can access the service from an Angular.js project. I have read that Angular supports CORS out of the box and all I needed to do was add this line: Header set Access-Control-Allow-Origin "*"
to my .htaccess file.
I've done this and my REST application is still working (no 500 internal server error from a bad .htaccess) but when I try to test it from test-cors.org it is throwing an error.
Fired XHR event: loadstart
Fired XHR event: readystatechange
Fired XHR event: error
XHR status: 0
XHR status text:
Fired XHR event: loadend
My .htaccess file looks like this
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ /index.php [QSA,L]
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT"
Is there something else I need to add to my .htaccess to get this to work properly or is there another way to enable CORS on my server?
As in this answer Custom HTTP Header for a specific file you can use
<File>
to enable CORS for a single file with this code:I tried @abimelex solution, but in Slim 3.0, mapping the OPTIONS requests goes like:
https://www.slimframework.com/docs/objects/router.html#options-route
It's look like you are using an old version of slim(2.x). You can just add following lines to .htaccess and don't need to do anything in PHP scripts.
This is what worked for me:
Thanks to Devin, I figured out the solution for my SLIM application with multi domain access.
In htaccess:
in index.php
Since I had everything being forwarded to index.php anyway I thought I would try setting the headers in PHP instead of the .htaccess file and it worked! YAY! Here's what I added to index.php for anyone else having this problem.
credit goes to slashingweapon for his answer on this question
Because I'm using Slim I added this route so that OPTIONS requests get a HTTP 200 response