Laravel-前端访问API接口报错-跨域问题

1、新建中间件

进入项目根目录,命令行执行

php artisan make:middleware EnableCrossRequestMiddleware

在app/Http/Middleware目录下多了EnableCrossRequestMiddleware.php文件


2、中间件内容

header('Access-Control-Allow-Origin', 'http://192.168.31.xxx:xxx','http://192.168.31.xxx','http://114.1xx.129.xx:xxx');
        $response->header('Access-Control-Allow-Headers', 'Origin, Content-Type, Cookie, Accept, multipart/form-data, application/json, Authorization');
        $response->header('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, OPTIONS');
        $response->header('Access-Control-Allow-Credentials', 'false');
        return $response;
    }
}

可以在Access-Control-Allow-Origin  后面指明允许访问接口的ip地址,或者精确到哪个ip的哪个端口。

如果要允许所有ip都可以访问API接口,可以将Access-Control-Allow-Origin  ,后改成*,此时也要确保Access-Control-Allow-Credentials不能为True

 public function handle($request, Closure $next)
    {

        $response = $next($request);
        $response->header('Access-Control-Allow-Origin', '*');  
        $response->header('Access-Control-Allow-Headers', 'Origin, Content-Type, Cookie, Accept, multipart/form-data, application/json, Authorization');
        $response->header('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, OPTIONS');
        $response->header('Access-Control-Allow-Credentials', 'false');
        return $response;
    }

3、然后在app/Http目录下的Kernel.php中$middleware里添加刚刚新增 的中间件

protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
        \App\Http\Middleware\EnableCrossRequestMiddleware::class,
    ];

然后跨域问题就解决啦

你可能感兴趣的:(PHP-Laravel)