Laravel API 允許跨域訪問

做冷欺花發表於2019-02-16

伺服器A請求伺服器B的介面,那麼一般會出現跨域問題。

XMLHttpRequest cannot load http://api.console.vms3.com/api/user. No `Access-Control-Allow-Origin` header is present on the requested resource. Origin `http://localhost:8080` istherefore not allowed access.

意思就是伺服器響應不允許跨域訪問.

那我們就需要讓伺服器支援跨域訪問, 也就是在響應頭部中新增

`Access-Control-Allow-Origin: *`

第一步: 建立中介軟體

建立 `app/Http/Middleware/AccessControlAllowOrigin.php` middleware 把 `Access-Control-Allow-Origin: *` 寫入頭部.
app/Http/Middleware/AccessControlAllowOrigin.php
<?php

namespace AppHttpMiddleware;

use Closure;
use IlluminateSupportFacadesAuth;

class AccessControlAllowOrigin
{
    /**
     *
     * Handle an incoming request.
     *
     * @param  IlluminateHttpRequest  $request
     * @param  Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        header(`Access-Control-Allow-Origin: *`);
        header("Access-Control-Allow-Credentials: true");
        header("Access-Control-Allow-Methods: *");
        header("Access-Control-Allow-Headers: Content-Type,Access-Token");
        header("Access-Control-Expose-Headers: *");

        return $next($request);
    }

}

第二步: 註冊路由

註冊這個 middlewarekernel 中.
分別在 protected $middleware 陣列中和 protected $routeMiddleware 陣列中
新增我們剛才建立的那個檔案class名, 使用 cors 這個別名.

第三步: 設定中介軟體保護介面

然後在設定它保護 api , 就是$middlewareGroups[`api`] 的陣列中新增它的別名, 本文中是 `cors`
app/Http/Kernel.php

<?php

namespace AppHttp;

use IlluminateFoundationHttpKernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application`s global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        IlluminateFoundationHttpMiddlewareCheckForMaintenanceMode::class,
        IlluminateFoundationHttpMiddlewareValidatePostSize::class,
        AppHttpMiddlewareTrimStrings::class,
        IlluminateFoundationHttpMiddlewareConvertEmptyStringsToNull::class,
        AppHttpMiddlewareAccessControlAllowOrigin::class,
    ];

    /**
     * The application`s route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        `web` => [
            AppHttpMiddlewareEncryptCookies::class,
            IlluminateCookieMiddlewareAddQueuedCookiesToResponse::class,
            IlluminateSessionMiddlewareStartSession::class,
            // IlluminateSessionMiddlewareAuthenticateSession::class,
            IlluminateViewMiddlewareShareErrorsFromSession::class,
            AppHttpMiddlewareVerifyCsrfToken::class,
            IlluminateRoutingMiddlewareSubstituteBindings::class,
        ],

        `api` => [
            `throttle:60,1`,
            `bindings`,
            `cors`
        ],
    ];

    /**
     * The application`s route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        `auth` => IlluminateAuthMiddlewareAuthenticate::class,
        `auth.basic` => IlluminateAuthMiddlewareAuthenticateWithBasicAuth::class,
        `bindings` => IlluminateRoutingMiddlewareSubstituteBindings::class,
        `can` => IlluminateAuthMiddlewareAuthorize::class,
        `guest` => AppHttpMiddlewareRedirectIfAuthenticated::class,
        `throttle` => IlluminateRoutingMiddlewareThrottleRequests::class,
        `cors` => AppHttpMiddlewareAccessControlAllowOrigin::class,
    ];
}

第四步:在路由中新增路由

Route::middleware(`cors`)->group(function () {
    //
});

相關文章