在使用laravel提供api服务时,是要允许跨域的,不然的浏览器里的JS是获取不到api接口的响应信息的,会报如下错误:
jquery.min.js:5 Cross-Origin Read Blocking (CORB) blocked cross-origin response http://127.0.0.1:8000/api/test with MIME type application/json. See https://www.chromestatus.com/feature/5629709824032768 for more details.
跨域在单纯的php里面是很好处理的,只要在页面头部加一个http header就行,代码 header('Access-Control-Allow-Origin: *');
<?php
header("Content-type:application/json; charset=utf-8");
header('Access-Control-Allow-Origin: *');
echo json_encode(['msg'=>'this message come from the api server.']);
为了让laravel能够响应跨域请求,今天网络上查找了很长时间,得到如下解决方案
- 创建中间件:
php artisan make:middleware Cors
,生成的文件路径:app/Http/Middleware/Cors.php - 修改刚才创建的中间件,修改handle函数如下:
public function handle($request, Closure $next)
{
return $next($request)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
}
- 最后把这个中间件添加到 app/Http/Kernel.php 里面的middlewareGroups 的api分组里
'api' => [
'throttle:60,1',
'bindings',
\App\Http\Middleware\Cors::class,
],
添加完成后,再测试就能收到从api返回的响应内容了。
还有一种方法是使用barryvdh/laravel-cors这个包(github: https://github.com/barryvdh/laravel-cors ),但是我在折腾很长时间之后也没能实现跨域请求,所以放弃了这种方法。
注:本文所用的Laravel版本为Laravel 6.7。