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 协议》,转载必须注明作者和本文链接
本帖由系统于 4年前 自动加精
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 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年前 评论

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