在阅读了很多问题/答案后,我决定发帖.我认为Slim Framework – jQuery $.ajax request – Method DELETE is not allowed by Access-Control-Allow-Methods总结了我发现并尝试过的大部分信息.
我正在使用MAMP和PHP 5.6进行开发,但生产环境很可能是共享主机.我也在使用ember.js
当ember执行POST请求时,我得到Access-Cross-Origin消息:
XMLHttpRequest cannot load 07001. No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘07002’ is therefore not allowed access.
我知道在服务器上设置适当的标头可以解决问题,但我不知道何时这样做.我目前在Slim框架中做的是:
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Content-Type');
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
$app->options('/(:name+)', function() use($app) {
$response = $app->response();
$app->response()->status(200);
$response->header('Access-Control-Allow-Origin', '*');
$response->header('Access-Control-Allow-Headers', 'Content-Type, X-Requested-With, X-authentication, X-client');
$response->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
});
但是,我检查了Ember.js请求,它没有请求OPTIONS,因此没有设置正确的标头.
如果我在Slim的单个路径中设置标题,那么它可以正常工作.但我不想一个接一个地在每条路线上设置标题.
如何设置所有路由的标头?
解决方法:
CorsSlim是你的朋友:
<?php
$app = new \Slim\Slim();
$corsOptions = array(
"origin" => "*",
"exposeHeaders" => array("Content-Type", "X-Requested-With", "X-authentication", "X-client"),
"allowMethods" => array('GET', 'POST', 'PUT', 'DELETE', 'OPTIONS')
);
$cors = new \CorsSlim\CorsSlim($corsOptions);
$app->add($cors);