业务需要,前后端是分离的,那这边访问的域名也是不一样的,这就存在跨域的问题,跨域请求的解决方案有 CORS 和 JSONP(了解更多明细可以参考这篇教程),但是 JSONP 有个致命缺点 —— 仅支持 GET 请求,所以推荐使用 CORS(Cross-origin resource sharing,跨域资源共享),一般情况下,这个都是用自定义中间件来解决问题。
1:使用 make:middleware这个 Artisan 命令创建中间件:
php artisan make:middleware CrossHttp
2:中间件App\Http\Middleware\CrossHttp代码如下:
<?php
namespace App\Http\Middleware;
use Closure;
class CrossHttp
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next) {
$response = $next($request);
$response->header('Access-Control-Allow-Origin', '*'); //允许所有资源跨域
$response->header('Access-Control-Allow-Headers', 'Origin, Content-Type, Cookie, Accept, Authorization, application/json , X-Auth-Token');//允许通过的响应报头
$response->header('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, OPTIONS, DELETE');//允许的请求方法
$response->header('Access-Control-Expose-Headers', 'Authorization');//允许axios获取响应头中的Authorization
$response->header('Allow', 'GET, POST, PATCH, PUT, OPTIONS, delete');//允许的请求方法
$response->header('Access-Control-Allow-Credentials', 'true');//运行客户端携带证书式访问
return $response;
}
}
3:注册路由,设置中间件保护接口
文件地址:\App\Http\Kernel.php
/**
* 中间件组
*
* The application's route middleware groups.
*
* @var array
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
// 这个是我们自定义的中间件
\App\Http\Middleware\CrossHttp::class,
],
'api' => [
'throttle:60,1',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
];
以上大概就是laravel跨域解决的方法了,laravel还提供了一个跨域的插件Laravel—CORS,这个后期用到的话会补充进来。
原文链接:https://guanchao.site/index/article/articledetail.html?artid=AowGpccPu
有好的建议,请在下方输入你的评论。
网友评论