laravel之跨域请求(二)「建议收藏」

2022-08-09 19:09:16 浏览数 (1)

大家好,又见面了,我是你们的朋友全栈君。

1,方法一:通过扩展包解决

扩展包地址:barryvdh/laravel-cors

(1)安装,项目根目录

代码语言:javascript复制
composer require barryvdh/laravel-cors

Laravel 5.4 及以下版本需要手动在 config/app.php 中注册服务提供者:

代码语言:javascript复制
BarryvdhCorsServiceProvider::class,

(2)使用 全局使用的中间件,在app/Http/kernel.php 文件:

代码语言:javascript复制
protected $middleware = [
    // ...
    BarryvdhCorsHandleCors::class,
];

特定路由中应用 CORS

代码语言:javascript复制
protected $middlewareGroups = [
    'web' => [
       // ...
    ],

    'api' => [
        // ...
        BarryvdhCorsHandleCors::class,
    ],

(3)配置 自定义配置,laravel-cors 扩展包的配置文件发布到 config 目录下:

代码语言:javascript复制
php artisan vendor:publish --provider="BarryvdhCorsServiceProvider" 

以下是该配置文件默认配置值(config/cors.php):

代码语言:javascript复制
eturn [

    /* |-------------------------------------------------------------------------- | Laravel CORS |-------------------------------------------------------------------------- | | allowedOrigins, allowedHeaders and allowedMethods can be set to array('*') | to accept any value. | */

    'supportsCredentials' => false,
    'allowedOrigins' => ['*'],
    'allowedOriginsPatterns' => [],
    'allowedHeaders' => ['*'],
    'allowedMethods' => ['*'],
    'exposedHeaders' => [],
    'maxAge' => 0,

];

以上步骤操作完,发起请求会报403错误,具体没找原因,知道小伙伴,可留言。

在gitHub上面找到了问题:

我使用的是 laravel 5.7 api dingo laravel-cors not work,需要在 config/app.php 中操注册服务提供者:

代码语言:javascript复制
'providers' => [
	BarryvdhCorsServiceProvider::class	
]

所以上面提到的laravel5.4<=版本需要添加,这个需要根据具体情况而定。

2,方法二:通过自定义中间件解决

1,新建一个中间件

代码语言:javascript复制
php artisan make:middleware EnableCrossRequestMiddleware

2.CrossRequestMiddleware.php

代码语言:javascript复制
?php
namespace AppHttpMiddleware;
use Closure;
class CrossRequestMiddleware
{ 
   
    /** * Handle an incoming request. * * @param IlluminateHttpRequest $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 = [
            'http://localhost:8000',
        ];
        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,DELETE');
            $response->header('Access-Control-Allow-Credentials', 'true');
        }
        return $response;
    }
}

3,全局使用,注册该中间件

代码语言:javascript复制
 protected $middleware = [
        // more
        AppHttpMiddlewareCrossRequestMiddleware::class,
    ];

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/105842.html原文链接:https://javaforall.cn

0 人点赞