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

    添加如下中间件:

    1. <?php
    2. namespace App\Http\Middleware;
    3. use Closure;
    4. class CrossHttp
    5. {
    6. /**
    7. * Handle an incoming request.
    8. *
    9. * @param \Illuminate\Http\Request $request
    10. * @param \Closure $next
    11. * @return mixed
    12. */
    13. public function handle($request, Closure $next)
    14. {
    15. if($request->getMethod() == "OPTIONS") {
    16. $allowOrigin = [
    17. 'http://192.168.1.47',
    18. 'http://localhost',
    19. ];
    20. $Origin = $request->header("Origin");
    21. if(in_array($Origin, $allowOrigin)){
    22. return response()->json('ok', 200, [
    23. # 下面参数视request中header而定
    24. 'Access-Control-Allow-Origin' => $Origin,
    25. 'Access-Control-Allow-Headers' => 'x-token',
    26. 'Access-Control-Allow-Methods' => 'GET,POST,OPTIONS']);
    27. } else {
    28. return response()->json('fail', 405);
    29. }
    30. }
    31. $response = $next($request);
    32. $response->header('Access-Control-Allow-Origin', '*');
    33. return $response;
    34. }
    35. }

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

    1. $app->middleware([
    2. \App\Http\Middleware\CrossHttp::class,
    3. ]);