美文网首页
Laravel/Luman跨域写法

Laravel/Luman跨域写法

作者: gurlan | 来源:发表于2019-02-27 14:11 被阅读0次

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,
]);

相关文章

网友评论

      本文标题:Laravel/Luman跨域写法

      本文链接:https://www.haomeiwen.com/subject/cwxfuqtx.html