在日常的对接工作中,经常会碰到跨域
常用的就是nginx设置
在hyperf中如何实现,我们只需要创建一个中间件即可
<?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', 'uid,token,Keep-Alive,User-Agent,Cache-Control,Content-Type');
Context::set(ResponseInterface::class, $response);
if ($request->getMethod() == 'OPTIONS') {
return $response;
}
return $handler->handle($request);
}
}
然后注册中间件
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 group@hyperf.io
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/
return [
'http' => [
// 数组内配置您的全局中间件,顺序根据该数组的顺序
\Hyperf\Session\Middleware\SessionMiddleware::class,
\App\Middleware\CorsMiddleware::class
],
];
这个时候再次请求接口会发现Response Headers中以下内容,说明成功
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: uid,token,Keep-Alive,User-Agent,Cache-Control,Content-Type
Access-Control-Allow-Origin: *
Connection: keep-alive
Content-Encoding: gzip
Content-Length: 59
Content-Type: application/json
Date: Fri, 31 Dec 2021 04:03:47 GMT
Server: Hyperf
Set-Cookie: HYPERF_SESSION_ID=U7seWQIStabjuzTPHsDbuAATNViHtX6jsuDNIjCm; expires=Fri, 31-Dec-2021 09:03:47 GMT; path=/; domain=47.96.43.213; httponly
我们还可以在nginx中配置
location / {
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
add_header Access-Control-Allow-Headers 'uid,token,Keep-Alive,User-Agent,Cache-Control,Content-Type,Authorization';
if ($request_method = 'OPTIONS') {
return 204;
}
}
如果是laravel
框加,只需要在入口文件index.php中添加以下
header('Access-Control-Allow-Origin:*');
if($_SERVER['REQUEST_METHOD'] == 'OPTIONS'){
header('Access-Control-Allow-Methods: GET,POST,PUT,DELETE,OPTIONS,PATCH');
// 设置是否允许发送 cookies
header('Access-Control-Allow-Credentials: true');
// 设置允许自定义请求头的字段
header('Access-Control-Allow-Headers: Authorization,Content-Type,Content-Length,Accept-Encoding,X-Requested-with, Origin');
exit;
}
如有问题,可以QQ搜索群1028468525加入群聊,欢迎一起研究技术
转载请注明:hyperf中跨域中间件 出自老鄢博客 | 欢迎分享