在阅读了许多问题/答案后,我决定发布。我认为Slim Framework-jQuery$.ajax请求-访问控制不允许方法DELETE-允许方法总结了我发现和尝试的大部分信息。
我使用MAMP和PHP 5.6进行开发,但生产环境很可能是一个共享主机。我也在使用ember.js
当ember进行POST请求时,我会收到Access Cross Origin消息:
XMLHttpRequest无法加载http://foo.bar/。请求的资源上不存在"Access Control Allow Origin"标头。原点'http://localhost:4200因此不允许访问。
我知道在服务器上设置合适的头可以解决这个问题,但我不知道什么时候该做。我目前在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的单个路由中设置了头,那么它就可以正常工作。但我不想在每条路线上一个接一个地设置标题。
如何设置所有路由的标头?
与其在项目中添加新的包,不如执行以下
$app->add(function ($req, $res, $next) {
$response = $next($req, $res);
return $response
->withHeader('Access-Control-Allow-Origin', 'http://mysite')
->withHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Accept, Origin, Authorization')
->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS');
});
https://www.slimframework.com/docs/v3/cookbook/enable-cors.html
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);