hyperf2.1中使用中间件方式实现跨域功能流程步骤
新项目后台打算用vue,刚好遇到这个跨域问题:
请求登录接口的时候,出现如:Access-Control-Allow-Origin at ...
我这用的是hyperf2.1,也打算在后端处理该问题,所以把解决实现问题记录一下
环境:
centos7
hyperf2.1
vue2.5+
进入步骤:
新增中间件文件:
\hyperf\app\Middleware\CorsMiddleware.php
<?php
declare(strict_types=1);
namespace App\Middleware;
use Hyperf\Utils\Context;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
class CorsMiddleware implements MiddlewareInterface
{
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$response = Context::get(ResponseInterface::class);
$response = $response->withHeader('Access-Control-Allow-Origin', '*')
->withHeader('Access-Control-Allow-Credentials', 'true')
// Headers 可以根据实际情况进行改写。
->withHeader('Access-Control-Allow-Headers', 'DNT,Keep-Alive,User-Agent,Cache-Control,Content-Type,Authorization');
Context::set(ResponseInterface::class, $response);
if ($request->getMethod() == 'OPTIONS') {
return $response;
}
return $handler->handle($request);
}
}
在中间件配置文件中添加跨域中间件信息:(最底下那个)
\hyperf\config\autoload\middlewares.php
<?php
declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://hyperf.wiki
* @contact [email protected]
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/
return [
// 这里的 http 对应默认的 server name,如您需要在其它 server 上使用 Session,需要对应的配置全局中间件
'http' => [
\Hyperf\Session\Middleware\SessionMiddleware::class,
// 数组内配置您的全局中间件,顺序根据该数组的顺序
\Hyperf\Validation\Middleware\ValidationMiddleware::class,
//跨域
\App\Middleware\CorsMiddleware::class
],
];
重新请求一下,看看效果
vue请求:
web请求:
相关文章