Slim Framework 和 Ember.js 中的 Access-Control-Origin

jrl*_*sta 5 php slim ember.js

在阅读了许多问题/答案后,我决定发布。我认为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”标头。因此,不允许访问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');
 });
Run Code Online (Sandbox Code Playgroud)

但是,我检查了 Ember.js 请求并且它没有请求OPTIONS,因此没有设置正确的标头。

如果我在 Slim 的单个路由中设置标头,则它可以正常工作。但我不想在每条路线上一一设置标题。

我该怎么做才能为所有路由设置标头?

Tho*_*dez 5

您可以这样做,而不是向您的项目添加新包

$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');
}); 
Run Code Online (Sandbox Code Playgroud)

https://www.slimframework.com/docs/v3/cookbook/enable-cors.html


Dav*_*ore 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);
Run Code Online (Sandbox Code Playgroud)