laravel处理跨域请求
分类
php
·
发表于 2016-05-29 10:50:38
写webapi总离开不跨域问题,总结下自己在做laravel开发的处理跨域请求方案。
推荐使用dingo/api 扩展包
1、用laravel中间件,基于CORS 创建中间件CrossDomainMiddleware.php,代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 <?php namespace App \Http \Middleware ;use Closure ;class CrossDomainMiddleware { 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' ); $response ->header('Access-Control-Allow-Methods' , 'GET, POST, PATCH, PUT, OPTIONS' ); $response ->header('Access-Control-Allow-Credentials' , 'true' ); return $response ; } }
在Kernel.php中注册中间件:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 <?php namespace App \Http ;use Illuminate \Foundation \Http \Kernel as HttpKernel ;class Kernel extends HttpKernel { protected $middleware = [ \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class, ]; protected $middlewareGroups = [ 'web' => [ \App\Http\Middleware\EncryptCookies::class, \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, \Illuminate\Session\Middleware\StartSession::class, \Illuminate\View\Middleware\ShareErrorsFromSession::class, \App\Http\Middleware\VerifyCsrfToken::class, ], 'api' => [ 'throttle:60,1' , \App\Http\Middleware\CrossDomainMiddleware::class, ] ]; protected $routeMiddleware = [ 'auth' => \App\Http\Middleware\Authenticate::class, 'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class, 'auth.basic.once' => \App\Http\Middleware\AuthenticateOnceWithBasicAuth::class, 'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class, 'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class, ]; }
1 2 3 4 5 6 7 http { ...... add_header Access-Control-Allow-Origin *; add_header Access-Control-Allow-Headers X-Requested-With; add_header Access-Control-Allow-Methods GET ,POST ,OPTIONS; ...... }
3、nginx的反向代理 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 upstream serve { server 127.0 .0 .1 :3000; keepalive 64 ; } server { listen 80 ; server_name localhost; location / { proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_set_header X-Nginx-Proxy true ; proxy_set_header Connection "" ; proxy_pass http://serve; } }