由于公司需要,要跨域提交客户网站的信息过来,所以整体就遇到了laravel项目的CORS error的问题! 原理是由于laravel框架中默认集成了CORS的验证机制,跨域访问将不会携带CORS默认的信息头,信息匹配不上,从而报错! 现在把解决方法贴上了,做个记录!
1.需要创建一个中间件,来替代系统默认的认证功能
php artisan make:middleware CORS
2.修改【app/http/middleware/CORS.php】文件
public function handle(Request $request, Closure $next)
{
return $next($request)->header('Access-Control-Allow-Origin','*')
->header('Access-Control-Allow-Methods','POST, GET, OPTIONS, PUT, DELETE')
->header('Access-Control-Allow-Headers','Content-Type, Accept, Authorization, X-Requested-With');
}
3.注册中间件【app/http/Kernel.php】
protected $routeMiddleware = [
'CORS' => \App\Http\Middleware\CORS::class
];
4.配置路由
Route::group(['middleware' => ['CORS'],'namespace' => 'App\Http\Controllers'], function() {
Route::any('/ceshi', 'WebController@index')->name('ceshi');
});
5.添加跳过CORS的路由【app/http/middleware/VerifyCsrfToken.php】
protected $except = [
'ceshi',
];
至此,跨域就完成了,我这里是单路由接口跨域,大家如果需要全域名跨域,可以去搜索取消laravel的cors验证!
|