Home >PHP Framework >Laravel >Implementation steps of Laravel API cross-domain access

Implementation steps of Laravel API cross-domain access

不言
不言forward
2018-10-26 16:36:533965browse

The content of this article is about the implementation steps of Laravel API cross-domain access. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

If server A requests the interface of server B, cross-domain problems will generally occur.

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.

means that the server response does not allow cross-domain access.

Then we need to enable the server to support cross-domain access, that is, add

'Access-Control-Allow-Origin: *'

to the response header. Step one: Create middleware

创建 `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);
    }

}

Step two: Register routing

Register thismiddleware to kernel.
In # respectively ##protected $middleware Array and protected $routeMiddleware ArrayAdd the
class name of the file we just created, use cors this Alias.

Step 3: Set the middleware protection interface

Then set it to protect the api, which is to add it to the array of

$middlewareGroups['api'] Alias, in this article it is '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,
    ];
}
Step 4: Add routing in routing

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

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

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