如何在PHP/Laravel5中設定CORS header




CORS是什麼?

CORS(Cross-Origin Resource Sharing)簡單來說就是跨網站資源存取,出於安全性必須要在伺服端加入 header 這樣 javascript 的請求才不會被封鎖

PHP 寫法

<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: X-Requested-With, Content-Type, Accept');
// code here

Laravel 寫法

建立中間件

$ php artisan make:middleware Cors

Cors.php

<?php

namespace AppHttpMiddleware;

use Closure;

class Cors
{
    /**
     * Handle an incoming request.
     *
     * @param  IlluminateHttpRequest  $request
     * @param  Closure  $next
     * @return mixed
     */
    public function handle($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');
    }
}

到Kernel.php註冊

protected $routeMiddleware = [
        'auth' => AppHttpMiddlewareAuthenticate::class,
        'auth.basic' => IlluminateAuthMiddlewareAuthenticateWithBasicAuth::class,
        'can' => IlluminateFoundationHttpMiddlewareAuthorize::class,
        'guest' => AppHttpMiddlewareRedirectIfAuthenticated::class,
        'throttle' => IlluminateRoutingMiddlewareThrottleRequests::class,
        'cors' => AppHttpMiddlewareCors::class, // <<< add this line
    ];

在路由中像一般middleware使用

//api
Route::group(['prefix' => 'api', 'middleware' => 'cors'],function(){
} 

關鍵字

No 'Access-Control-Allow-Origin' header is present on the requested resource

laravel CORS header

PHP CORS header

參考

http://en.vedovelli.com.br/2015/web-development/Laravel-5-1-enable-CORS/

https://blog.toright.com/posts/3205/%E5%AF%A6%E4%BD%9C-cross-origin-resource-sharing-cros-%E8%A7%A3%E6%B1%BA-ajax-%E7%99%BC%E9%80%81%E8%B7%A8%E7%B6%B2%E5%9F%9F%E5%AD%98%E5%8F%96-request.html

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

這個網站採用 Akismet 服務減少垃圾留言。進一步瞭解 Akismet 如何處理網站訪客的留言資料