首頁 > php框架 > Laravel > 主體

Laravel API跨域存取的實作步驟

不言
發布: 2018-10-26 16:36:53
轉載
3944 人瀏覽過

這篇文章帶給大家的內容是關於Laravel API跨域存取的實現步驟,有一定的參考價值,有需要的朋友可以參考一下,希望對你有幫助。

伺服器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 App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;

class AccessControlAllowOrigin
{
    /**
     *
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        header(&#39;Access-Control-Allow-Origin: *&#39;);
        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 App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application&#39;s global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
        \App\Http\Middleware\AccessControlAllowOrigin::class,
    ];

    /**
     * The application&#39;s route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        &#39;web&#39; => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            // \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],

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

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used inpidually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'cors' => \App\Http\Middleware\AccessControlAllowOrigin::class,
    ];
}
登入後複製

第四步:在路由中加入路由

#
Route::middleware('cors')->group(function () {
    //
});
登入後複製

以上是Laravel API跨域存取的實作步驟的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:segmentfault.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板