1,创建CrossHttp中间件

<?php
/**
 * Created by PhpStorm.
 * User: cnbattle
 * Date: 18-10-22
 * Time: 下午12:40
 */

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://admin.580xb.cn',
            ];
            $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-requested-with,content-type,Authorization,CityCode',
                    'Access-Control-Allow-Methods' => 'POST,DELETE,GET,PUT,OPTIONS']);
            } else {
                return response()->json('fail', 405);
            }
        }

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

2,bootstrap/app.php 文件内,添加全局中间件

$app->middleware([
    App\Http\Middleware\CrossHttp::class
]);
来源:中战博客,欢迎分享!
标签: laravel,lumen,cors,middleware