简体   繁体   中英

CORS slim framework. Angular request to apache not working

I have a chorme plugin that allows me to toggle CORS by inserting a header. If I use that my slim code works. If not then I get an error as follows.

(index):1 XMLHttpRequest cannot load http://localhost/api/flowers . No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin ' http://localhost:9000 ' is therefore not allowed access.

My code

$app = new \\Slim\\Slim();
$app->response->headers->set('Content-Type', 'application/json'); $app->response->header('Access-Control-Allow-Headers',> 'Content-Type'); $app->response->header('Access-Control-Allow-Methods', 'GET, PUT, POST, DELETE');
$app->response->header('Access-Control-Allow-Origin','*');

$app->get('/', function() use($app){

$ins = new Lead();
$products = $ins->run();
echo json_encode($products); });

If I use the crome extension then the header response from the server is as follows.

HTTP/1.1 200 OK Date: Wed, 16 Dec 2015 23:04:26 GMT Server: Apache/2.4.7 (Ubuntu) X-Powered-By: PHP/5.5.9-1ubuntu4.14 Access-Control-Allow-Headers: Content-Type Access-Control-Allow-Methods: GET, PUT, POST, DELETE Access-Control-Allow-Origin: * Keep-Alive: timeout=5, max=100 Connection: Keep-Alive Transfer-Encoding: chunked Content-Type: application/json

So the headers are being sent. But CORS still does not work without the extension. I need to fix this for all browsers of course. Not just mine. I'm pretty sure its a small mistake but I'm not seing it. What's wrong here?

Your system needs to handle "options" routes.

Browsers use an OPTIONS request at the same URL. So essentially you need to handle 2 requests.

If you add in a $app->options("/:name+"); it should fix it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM