Home  >  Article  >  PHP Framework  >  Detailed explanation of Laravel API allowing cross-domain access

Detailed explanation of Laravel API allowing cross-domain access

藏色散人
藏色散人forward
2020-11-20 14:29:186741browse

下面由Laravel框架教程栏目给大家介绍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

第二步: 注册路由

注册这个 middlewarekernel 中.
分别在 protected $middleware  数组中和 protected $routeMiddleware 数组中
添加我们刚才创建的那个文件class名, 使用 cors 这个别名.

第三步: 设置中间件保护接口

然后在设置它保护 api , 就是$middlewareGroups['api'] 的数组中添加它的别名, 本文中是 'cors'
app/Http/Kernel.php

 [
            \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 () {
    //
});

The above is the detailed content of Detailed explanation of Laravel API allowing cross-domain access. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete