介绍

laravel api跨域问题

新建一个中间件

php artisan make:middleware EnableCrossRequestMiddleware

书写中间件内容

<?php
namespace App\Http\Middleware;
use Closure;
class EnableCrossRequestMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $response = $next($request);
        $origin = $request->server('HTTP_ORIGIN') ? $request->server('HTTP_ORIGIN') : '';
        $allow_origin = [
            'http://localhost:8000',
            'http://shudong.wang',
        ];
        if (in_array($origin, $allow_origin)) {
            $response->header('Access-Control-Allow-Origin', $origin);
            $response->header('Access-Control-Allow-Headers', 'Origin, Content-Type, Cookie, X-CSRF-TOKEN, Accept, Authorization, X-XSRF-TOKEN');
            $response->header('Access-Control-Expose-Headers', 'Authorization, authenticated');
            $response->header('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, OPTIONS');
            $response->header('Access-Control-Allow-Credentials', 'true');
        }
        return $response;
    }
}

$allow_origin 数组变量就是你允许跨域的列表了,可自行修改。

然后在内核文件注册该中间件

protected $middleware = [
// more
App\Http\Middleware\EnableCrossRequestMiddleware::class,
];

在 App\Http\Kernel 类的 $middleware 属性添加,这里注册的中间件属于全局中间件。

然后你就会发现前端页面已经可以发送跨域请求了。

会多出一次 method 为 options 的请求是正常的,因为浏览器要先判断该服务器是否允许该跨域请求。

$response->headers->add(['Access-Control-Allow-Origin' => $origin]);
$response->headers->add(['Access-Control-Allow-Headers' => 'Origin, Content-Type, Cookie,X-CSRF-TOKEN, Accept,Authorization']);
$response->headers->add(['Access-Control-Expose-Headers' => 'Authorization,authenticated']);
$response->headers->add(['Access-Control-Allow-Methods' => 'GET, POST, PATCH, PUT, OPTIONS']);
$response->headers->add(['Access-Control-Allow-Credentials' => 'true']);
$app->router->group([
    'prefix'     => 'api',
    'middleware' => ['cross','api'],
], function ($router) {
    $router->options('/{path:.*}', function ($path) {});
    require __DIR__ . '/../routes/api.php';
});
bootstrap/app.php