laravel 接口 ajax跨域,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,

];

然后跨域问题就解决啦

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值