Laravel/Luman跨域写法

2019-02-27  本文已影响0人  gurlan

1.新建中间件Cors.php

<?php

namespace App\Http\Middleware;

use Closure;

class Cors
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure                 $next
     * @param string|null              $guard
     *
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null)
    {
        //Intercepts OPTIONS requests
        if ($request->isMethod('OPTIONS')) {
            $response = response('', 200);
        } else {
            // Pass the request to the next middleware
            $response = $next($request);
        }

        // Adds headers to the response
       $response->header('Access-Control-Allow-Origin', '*');
        $response->header('Access-Control-Allow-Credentials', 'true');
        $response->header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, x-token");
        $response->header("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");

        // Sends it
        return $response;
    }
}

2.注册中间件,修改bootstrap/app.php

$app->middleware([
    'cors' => App\Http\Middleware\Cors::class,
]);
上一篇 下一篇

猜你喜欢

热点阅读