laravel 跨域解决方案

laravel 跨域解决方案,第1张

laravel 跨域解决方案 我们在用 laravel 进行开发的时候,特别是前后端完全分离的时候,由于前端项目运行在自己机器的指定端口(也可能是其他人的机器) , 例如 localhost:8000 , 而 laravel 程序又运行在另一个端口,这样就跨域了,而由于浏览器的同源策略,跨域请求是非法的。其实这个问题很好解决,只需要添加一个中间件就可以了。

1.新建一个中间件

php artisan make:middleware EnableCrossRequestMiddleware

2.书写中间件内容

<?php
namespace App\Http\Middleware;
use Closure;
class EnableCrossRequestMiddleware
{
    /**
     * 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://localhost:8000',
        ];
        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;
    }
}

$allow_origin 数组变量就是你允许跨域的列表了,可自行修改。

3.然后在内核文件注册该中间件

    protected $middleware = [
        // more
        App\Http\Middleware\EnableCrossRequestMiddleware::class,
    ];

在 App\Http\Kernel 类的 $middleware 属性添加,这里注册的中间件属于全局中间件。

然后你就会发现前端页面已经可以发送跨域请求了。

会多出一次 method 为 options 的请求是正常的,因为浏览器要先判断该服务器是否允许该跨域请求。

更多Laravel相关技术文章,请访问Laravel框架入门教程栏目进行学习!

以上就是laravel 跨域解决方案的详细内容,

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/701770.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-23
下一篇 2022-04-23

发表评论

登录后才能评论

评论列表(0条)

保存