Laravel 5.1 API启用Cors

Laravel 5.1 API启用Cors,第1张

Laravel 5.1 API启用Cors

这是我的CORS中间件

<?php namespace AppHttpMiddleware;use Closure;class CORS {        public function handle($request, Closure $next)    {        header("Access-Control-Allow-Origin: *");        // ALLOW OPTIONS METHOD        $headers = [ 'Access-Control-Allow-Methods'=> 'POST, GET, OPTIONS, PUT, DELETE', 'Access-Control-Allow-Headers'=> 'Content-Type, X-Auth-Token, Origin'        ];        if($request->getMethod() == "OPTIONS") { // The client-side application can set only headers allowed in Access-Control-Allow-Headers return Response::make('OK', 200, $headers);        }        $response = $next($request);        foreach($headers as $key => $value) $response->header($key, $value);        return $response;    }}

要使用CORS中间件,您必须先在app Http Kernel.php文件中注册它,如下所示:

protected $routeMiddleware = [        //other middlewares        'cors' => 'AppHttpMiddlewareCORS',    ];

然后您可以在路线中使用它

Route::get('example', array('middleware' => 'cors', 'uses' => 'ExampleController@dummy'));


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5151663.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-18
下一篇 2022-11-18

发表评论

登录后才能评论

评论列表(0条)

保存