lumen框架解决非简单请求 cors 跨域问题

属于 LaravelPHP前端 分类 0 评论 52 阅读

Lumen在做前后端分离项目时,在浏览器中访问,若前后端域名不一致会导致跨域问题,简单跨域好解决。若发送的是非简单跨域(参考文章),此时浏览器会先发送option请求进行预检,预检通过才发送真正的请求。此时服务端要实现option请求的接收。服务端代码实现如下:

添加如下中间件:

<?php

namespace App\Http\Middleware;

use Closure;

class CrossHttp
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if($request->getMethod() == "OPTIONS") {
            $allowOrigin = [
                'http://192.168.1.47',
                'http://localhost',
            ];
            $Origin = $request->header("Origin");
            if(in_array($Origin, $allowOrigin)){
                return response()->json('ok', 200, [
                    # 下面参数视request中header而定
                    'Access-Control-Allow-Origin' => $Origin,
                    'Access-Control-Allow-Headers' => 'x-token',
                    'Access-Control-Allow-Methods' => 'GET,POST,OPTIONS']);
            } else {
                return response()->json('fail', 405);
            }
        }

        $response = $next($request);
        $response->header('Access-Control-Allow-Origin', '*');
        return $response;
    }
}

在 boostrap/app.php 里注册一下全局中间件即可完成

$app->middleware([
     \App\Http\Middleware\CrossHttp::class,
]);
发表你的评论