在阅读了很多问题后,我决定发帖。我认为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无法加载 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的单个路径中设置标题,那么它可以正常工作。但我不想一个接一个地在每条路线上设置标题。
如何设置所有路线的标题?
答案 0 :(得分:3)
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);
答案 1 :(得分:3)
不是在项目中添加新包,而是可以执行此操作
$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