hyperf中跨域中间件

在日常的对接工作中,经常会碰到跨域

常用的就是nginx设置

在hyperf中如何实现,我们只需要创建一个中间件即可

```
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中注册一下

```
[
// 数组内配置您的全局中间件,顺序根据该数组的顺序
\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;
}
```

    A+
发布日期:2021年12月31日  所属分类:未分类

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: