我有一个带Slim Framework的小服务器(index.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);
$app->post('/foo', function () use ($app) {
...
echo "foo";
});
当我尝试使用Ionic(phonegap app)从我的应用程序(手机应用程序)攻击post方法时,我收到此消息:
XMLHttpRequest无法加载http://MY_IP/~FOLDER/foo。回应 预检请求未通过访问控制检查:否 请求中存在“Access-Control-Allow-Origin”标头 资源。因此不允许来源“http://192.168.0.157:8100” 访问。响应的HTTP状态代码为404.
代码:
$http.post(rest_service_url + '/foo', {
data: ...
}).then(
function(res){
console.log("OK");
},
function(err){
console.log("ERROR", err);
}
);
我在互联网上测试了这些解决方案,但是无人工作:
使用CorsSlim:
$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);
将其放入.htaccess
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT"
将此放在index.php
之上header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Content-Type');
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
在Slim创建后使用此功能:
$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');
});