Laravel6.X 跨域问题解决方案

简要说明:新项目比较小,所以尝试了6.0版本的Laravel框架。之前的项目用的是barryvdh/laravel-cors这个包,但是目前不支持6.X系统的,所以贴出这个项目的解决方案。

自定义中间件

第一步:创建中间件
php artisan make:middleware EnableCrossRequestMiddleware
第二步:编辑中间件
<?php
namespace App\Http\Middleware;
use Closure;
class EnableCrossRequestMiddleware{
    /**
     * @param $request
     * @param Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        header('Content-Type: text/html;charset=utf-8');
        header('Access-Control-Allow-Origin:*');
        header('Access-Control-Allow-Methods:POST,GET,PUT,OPTIONS,DELETE'); // 允许请求的类型
        header('Access-Control-Allow-Credentials: true'); // 设置是否允许发送 cookies
        header('Access-Control-Allow-Headers: Content-Type,Access-Control-Allow-Origin,Access-token,Content-Length,Accept-Encoding,X-Requested-with, Origin,Access-Control-Allow-Methods'); // 设置允许自定义请求头的字段

        return $next($request);

    }
}
第三步:注册中间件(全局)
<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
      //other
        \App\Http\Middleware\EnableCrossRequestMiddleware::class,
    ];
本作品采用《CC 协议》,转载必须注明作者和本文链接
空舟湖上~      ——Jouzeyu
附言 1  ·  4年前

好吧,可能是我安装的版本有误,大家就当这是一个简单的自定义跨域吧,哈哈

lochpure
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
讨论数量: 7

是支持的哦

4年前 评论
Fringe 4年前
$response=$next($request);
$headers = [
    "Content-Type" => "text/html;charset=utf-8"
];
return $response->withHeaders($headers);
4年前 评论

为什么不在 nginx 中解决……

4年前 评论
eanBear 4年前
Tricker (作者) 4年前

composer require barryvdh/laravel-cors (他不香嘛?)

4年前 评论
medz

:kissing_heart: https://github.com/medz/cors 哈哈~

4年前 评论

不是不支持,是namespace换了

4年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!