Laravel在Uniapp跨域请求API的时候出现错误解决方案

在前端跨域请求API接口的时候提示如下信息:

XMLHttpRequest cannot load http://zhushou.io/api/depot. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' istherefore not allowed access.

原因是需要添加跨域请求设置的中间件,允许跨域请求:

先增加Middleware中间件文件AccessControlAllowOrigin.php

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;

class AccessControlAllowOrigin
{
    public function handle($request, Closure $next)
    {
        header('Access-Control-Allow-Origin: *');
        header("Access-Control-Allow-Credentials: true");
        header("Access-Control-Allow-Methods: *");
        header("Access-Control-Allow-Headers: Content-Type,Access-Token");
        header("Access-Control-Expose-Headers: *");

        return $next($request);
    }

}

然后需要注册中间件文件,Kernel.php里面:

protected $middleware 下面新增:\App\Http\Middleware\AccessControlAllowOrigin::class
protected $routeMiddleware下面新增:'cors'=> \App\Http\Middleware\AccessControlAllowOrigin::class,

最后在api.php使用中间件即可:

Route::namespace('api')->middleware('cors')->group(function () {
    //院校库
    Route::get('/schools/depot','schools\Depot@index');
});

发表评论

电子邮件地址不会被公开。 必填项已用*标注