I'm facing challenges in setting up CORS with Slim and AngularJS.
AngularJS HTTP Request:
$http({
method: 'GET',
headers: {
'Content-Type': 'application/json',
Accepts: 'application/json'
},
url: 'https://apisite/v1/users/'
})
.success(function(data){
users.users_list = data.results;
})
.error(function(){
});
Using Slim on the API server, I have the following setup:
use Slim\Slim as Slim;
Slim::registerAutoloader();
$slim = new Slim();
$http_origin = $slim->request->headers->get('Origin');
$slim->response->headers->set('Access-Control-Allow-Origin', '*');
$slim->response->headers->set('Access-Control-Allow-Credentials', 'true');
$slim->response->headers->set('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE,OPTIONS');
$slim->response->headers->set('Access-Control-Allow-Headers', 'Origin, Content-Type, Accept, Authorization');
//Routes are defined here
$slim->run();
Although setting headers for every request is not ideal, it resolves the preflight error on Access-Control-Allow-Origin
. However, I'm now encountering a preflight error on OPTIONS
each time I try to access the API. I'm struggling to return a success in Slim for a preflight options check.
I've attempted to add conditional steps to handle options requests and set headers:
if($slim->request->isOptions()){
header("HTTP/1.1 200 OK");
}
Unfortunately, this approach doesn't seem to have any impact. I also tried creating a generic route for all OPTIONS
requests, but it didn't work either.
$slim->options('/(:request/)', function () use ($slim){
header("HTTP/1.1 200 OK");
});
I understand that the solution might be simple, and my lack of understanding about the request process between the two servers and the required headers is likely causing the issue. Any assistance would be greatly appreciated.
Error message observed when attempting to load the AngularJS page:
OPTIONS https://apisite/api/v1/users/
(anonymous function) @ angular.js:10514sendReq @ angular.js:10333serverRequest @ angular.js:10045processQueue @ angular.js:14567(anonymous function) @ angular.js:14583Scope.$eval @ angular.js:15846Scope.$digest @ angular.js:15657Scope.$apply @ angular.js:15951done @ angular.js:10364completeRequest @ angular.js:10536requestLoaded @ angular.js:10477
XMLHttpRequest cannot load https://apisite/api/v1/users/. Response for preflight has invalid HTTP status code 404