当使用前后端分离,并且前端后端域名不统一时,我遇到了跨域的问题
1 | Access to XMLHttpRequest at http://localhost/api/login from origin http://localhost:8010 has been blocked by CORS policy: Response to preflight request doesnt pass access control check: NoAccess-Control-Allow-Origin header is present on the requested resource.``` |
1 | Access to XMLHttpRequest at http://localhost/api/login from origin http://localhost:8010 has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response. |
我们只需要在返回的 response
中添加 header
就可以了
首先我们创建一个 Filter
用来批量在生成的 response
中添加 headers
1 | App\Filters\Api.php |
接下来我们将注册并配置 App\Filters\Api::class
, 编辑配置文件 App\Config\Filters.php
1 | ... |
配置该 filter 对哪些 uri 生效
public $filters = [
api => [
after =>[
api/*,
]
]
];
至此,在每个路径为 api/*
的请求返回前,就会执行 after
中的代码,添加 headers