Laravel5.7 跨域解决

先检查app/Http/Middleware/ 下是否有EnableCrossRequestMiddleware.php 这个文件,没有此文件使用此命令创建

php artisan make:middleware EnableCrossRequestMiddleware

然后修改EnableCrossRequestMiddleware.php 的handle

     /**
 * Handle an incoming request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Closure  $next
 * @return mixed
 */
public function handle($request, Closure $next)
{
    $response = $next($request);
    $origin = $request->server('HTTP_ORIGIN') ? $request->server('HTTP_ORIGIN') : '';
    $allow_origin = [
        'http://127.0.0.1:8080',//允许访问
    ];
    if (in_array($origin, $allow_origin)) {
        $response->header('Access-Control-Allow-Origin', $origin);
        $response->header('Access-Control-Allow-Headers', 'Origin, Content-Type, Cookie, X-CSRF-TOKEN, Accept, Authorization, X-XSRF-TOKEN');
        $response->header('Access-Control-Expose-Headers', 'Authorization, authenticated');
        $response->header('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, OPTIONS');
        $response->header('Access-Control-Allow-Credentials', 'true');
    }
    return $response;
}

然后找到app/Http/Kernel.php文件中的 protected $middleware

    protected $middleware = [
    \App\Http\Middleware\CheckForMaintenanceMode::class,
    \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
    \App\Http\Middleware\TrimStrings::class,
    \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    \App\Http\Middleware\TrustProxies::class,
    \App\Http\Middleware\EnableCrossRequestMiddleware::class,//新增跨域中间件
];
本作品采用《CC 协议》,转载必须注明作者和本文链接
本帖由系统于 5年前 自动加精
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
讨论数量: 5

可以尝试使用这个laravel 官方依赖包

composer install barryvdh/laravel-cors

laravel-cors 文档

文档介绍

6年前 评论

可以尝试使用这个laravel 官方依赖包

composer install barryvdh/laravel-cors

laravel-cors 文档

文档介绍

6年前 评论

@raybon 谢谢了, 很赞非常好用,你那边链接404了,可以换个https://laravelacademy.org/post/9273.html,

6年前 评论

@ZzyYeMen 已纠正,连接放成ssh了

6年前 评论
medz

哈哈,还以尝试下这个 medz/cors 拓展包,支持多种框架!laravel 框架还支持子模式

6年前 评论

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