前后端项目跨域访问时会遇到此问题,解决方法如下:

创建一个中间件

php artisan make:middleware EnableCrossRequestMiddleware

该中间件的文件路径为:app/Http/Middleware/EnableCrossRequestMiddleware.php

中间件 EnableCrossRequestMiddleware 内容如下:

<?php
/**
 * 跨域设置
 */

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Response;

class EnableCrossRequestMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $response = $next($request);

        $origin = $request->server('HTTP_ORIGIN') ? $request->server('HTTP_ORIGIN') : '';
        $allow_origin = config('origin.allowed');

        if (in_array($origin, $allow_origin)) {

            $response->header('Access-Control-Allow-Origin', $origin);
            $response->header('Access-Control-Allow-Headers', 'Origin, Content-Type, Cookie, X-CSRF-TOKEN, Accept, Authorization, X-XSRF-TOKEN');
            $response->header('Access-Control-Expose-Headers', 'Authorization, authenticated');
            $response->header('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, OPTIONS');
            $response->header('Access-Control-Allow-Credentials', 'true');
        }
        return $response;
    }
}

app/Http/Kernal.php 文件中将其注册为全局中间件

namespace App\Http;

use App\Http\Middleware\AuthenticateMain;
use App\Http\Middleware\AuthenticateSeller;
use App\Http\Middleware\AuthenticateUser;
use Illuminate\Foundation\Http\Kernel 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 = [
        \App\Http\Middleware\CheckForMaintenanceMode::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
        \App\Http\Middleware\TrustProxies::class,
        \App\Http\Middleware\EnableCrossRequestMiddleware::class, // 添加这一行将其注册为全局中间件
    ];
}

增加配置文件app/config/origin.php,内容为允许的域名

<?php
return [

    'allowed' => [
        'http://test.example.com',
        'http://test-fe.example.com:8080'
    ]

];

发表评论

电子邮件地址不会被公开。 必填项已用*标注