# 设置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