在阅读了许多问题/答案后,我决定发布。我想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 http://foo.bar/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.
我知道在服务器上设置适当的 header 可以解决问题,但我不知道何时进行。我目前在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
,因此没有设置正确的 header 。
如果我在 Slim 的单个路由中设置 header ,那么它可以正常工作。但我不想在每条路线上一个一个地设置 header 。
如何为所有路由设置 header ?
最佳答案
您可以这样做,而不是向您的项目添加新包
$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
关于php - Slim Framework 和 Ember.js 中的 Access-Control-Origin,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29337646/