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-08-16 16:09:30

    android WebView 注入js 几种方式

    有时我们开发中需要将js 注入到我们本地,有可能你会说,放在Web不就可以了吗,的确,但是需求就是这样的

  • 2020-11-05 23:20:29

    mac更新node版本

    initializer function 0x0 not in mapped image for /usr/local/bin/node,除了上面的问题 你或许还出现过 no such file or directory 这样的提示,总之更新完以后node直接不能用了。

  • 2020-11-07 16:31:02

    nginx配置X-Frame-Options允许多个域名iframe嵌套

    有时候我们需要允许多个url的来源,但是又不能全部开放,所以应该匹配第三种方法ALLOW-FROM url,那么多个url该如何配置呢,百度了所有网站都没有找到,那么这里写给大家,其实很简单: add_header X-Frame-Options 'ALLOW-FROM https://xxx.xxxxxx.com https://xxx2.xxxxxxx.com'; 就是使用空格隔开就好了!

  • 2020-11-08 08:31:51

    meteor在不同端口启动服务

    当没有任何参数时,run是默认行为,在幕后,它3000端口开启node.js服务器实例,同时开启监听3001端口的MongoDB服务