Laravel 跨域解决方案

2018-08-16 16:10:43

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

  1. 新建一个中间件

    php artisan make:middleware EnableCrossRequestMiddleware
  2. 书写中间件内容

    <?phpnamespace 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 的请求是正常的,因为浏览器要先判断该服务器是否允许该跨域请求。

  • 2020-12-07 22:06:13

    System Extension Blocked - warning

    After upgrading your macOS computer to High Sierra 10.13.4 or higher (starting in April 2018), you may see a message about a System Extension Blocked. At Williams we have seen this warning appear for these programs:

  • 2020-12-08 08:57:12

    win10上使用win-sshfs

    首先在GitHub上下载DokanSetup-1.0.5.1000和WinSSHFS-1.6.1.13-devel 注意:Dokan不能使用最新的版本,得使用1.0.5版本。要不win-sshfs会报Dokan版本错误的问题。(win10版本)

  • 2020-12-08 11:51:54

    Ubuntu安装Node.js和npm

    Node.js是基于Chrome的JavaScript构建的跨平台JavaScript运行时环境,npm是Node.js的默认程序包管理器,也是世界上最大的软件注册表。本篇文章展示了三种在Ubuntu 20.04服务器上安装Node.js和npm的方法。

  • 2020-12-08 17:13:57

    nvm卸载、安装node和npm

    1、node.js、nvm、 npm (1)在cmd中输入`where node`找到node长须所在位置进行删除 (2)确保计算机-环境变量删除相关引用 (3)在cmd中输入`node -v` ,得到以下结果,删除成功

  • 2020-12-08 17:23:36

    Window下完全卸载删除Nodejs

    1.从卸载程序卸载程序和功能。 2.重新启动(或者您可能会从任务管理器中杀死所有与节点相关的进程)。 3.寻找这些文件夹并删除它们(及其内容)(如果还有)。根据您安装的版本,UAC设置和CPU架构,这些可能或可能不存在: