# 設置CORS
CORS - Cross origin resource sharing
> 跨源資源共享
A good flowchart for implementing CORS support Reference:
> 實現CORS支持參考的良好流程圖:
[CORS server flowchart](http://www.html5rocks.com/static/images/cors_server_flowchart.png)
You can test your CORS Support here: http://www.test-cors.org/
You can read the specification here: https://www.w3.org/TR/cors/
## The simple solution
## 簡單的解決方案
For simple CORS requests, the server only needs to add the following header to its response:
> 對于簡單的CORS請求,服務器只需要在響應中添加以下頭信息:
~~~bash
Access-Control-Allow-Origin: <domain>, ...
~~~
The following code should enable lazy CORS.
> 下面的代碼應該啟用惰性CORS。
~~~php
$app->options('/{routes:.+}', function ($request, $response, $args) {
return $response;
});
$app->add(function ($request, $handler) {
$response = $handler->handle($request);
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');
});
~~~
Add the following route as the last route:
> 添加以下路由作為最后一條路由:
~~~php
<?php
use Slim\Exception\HttpNotFoundException;
/*
*如果所有路由都不匹配,則提供一個404 Not Found頁面
*注意:確保最后定義此路由
* Catch-all route to serve a 404 Not Found page if none of the routes match
* NOTE: make sure this route is defined last
*/
$app->map(['GET', 'POST', 'PUT', 'DELETE', 'PATCH'], '/{routes:.+}', function ($request, $response) {
throw new HttpNotFoundException($request);
});
~~~
## Access-Control-Allow-Methods
The following middleware can be used to query Slim’s router and get a list of methods a particular pattern implements.
> 以下中間件可用于查詢Slim的路由器,并獲得特定模式實現的方法列表。
Here is a complete example application:
> 下面是一個完整的示例應用程序:
~~~php
<?php
use Slim\Factory\AppFactory;
use Slim\Routing\RouteContext;
require __DIR__ . '/../vendor/autoload.php';
$app = AppFactory::create();
//這個中間件將在所有允許的方法中附加響應頭的訪問控制允許方法
// This middleware will append the response header Access-Control-Allow-Methods with all allowed methods
$app->add(function($request, $handler) {
$routeContext = RouteContext::fromRequest($request);
$routingResults = $routeContext->getRoutingResults();
$methods = $routingResults->getAllowedMethods();
$response = $handler->handle($request);
$response = $response->withHeader('Access-Control-Allow-Methods', implode(",", $methods));
return $response;
});
//路由中間件應該在我們的CORS中間件之后添加,所以先執行路由
// The RoutingMiddleware should be added after our CORS middleware so routing is performed first
$app->addRoutingMiddleware();
$app->get("/api/{id}", function($request, $response, $arguments) {
// ...
});
$app->post("/api/{id}", function($request, $response, $arguments) {
// ...
});
$app->map(["DELETE", "PATCH"], "/api/{id}", function($request, $response, $arguments) {
// ...
});
//在使用一些javascript前端框架和使用slim php中的組時,請注意這一點
// Pay attention to this when you are using some javascript front-end framework and you are using groups in slim php
$app->group('/api', function () {
//由于瀏覽器在發送PUT或DELETE請求時的行為,您必須添加OPTIONS方法。
// Due to the behaviour of browsers when sending PUT or DELETE request, you must add the OPTIONS method. Read about preflight.
$this->map(['PUT', 'OPTIONS'], '/{user_id:[0-9]+}', function ($request, $response, $arguments) {
// Your code here...
});
});
$app->run();
~~~
- 開始
- 安裝
- 升級指南
- Web服務器
- 概念
- 生命周期
- PSR 7
- 中間件
- 依賴容器
- 實例 及通知和警告處理
- Request
- 請求方法
- 請求頭信息
- 請求主體
- 上傳的文件
- 請求幫助
- 路由對象
- Response
- 響應狀態
- 響應標頭
- 響應體
- 返回JSON
- 視圖模板
- 路由
- 創建路由
- 路由回調
- 路由策略
- 路線占位符
- 路由名
- 路由組
- 路由中間件
- 路由表達式緩存
- 容器識別解析
- 封裝中間件
- 路由的中間件
- 錯誤處理中間件
- 方法重寫的中間件
- 輸出緩沖中間件
- 內容長度中間件
- 擴展功能
- 以 / 結尾的路由模式
- 獲取當前路由
- 設置CORS
- 使用POST表單上傳文件
- 第三方組件
- slim-session
- auth
- slim-api-skeleton
- dir