一、传统框架中
- 在传统框架中一般来说有两种方案
1,例如laravel入口文件index.php中加上允许跨域代码 2,通过nginx反向代理
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;
}
二、Hyperf解决方式
1,建立一个跨域中间件
<?php
/**
* Author:陈杰
* Blog:http://blog.95shouyou.com
* Email:823380606@qq.com
* Git:https://gitee.com/chen95
* Date:2020/12/8 0008
* Time:11:33
*/
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);
}
}
<?php
declare(strict_types=1);
return [
'http' => [
\App\Middleware\CorsMiddleware::class
],
];
2,使用nginx反向代理
# 至少需要一个 Hyperf 节点,多个配置多行
upstream a2admin {
# Hyperf HTTP Server 的 IP 及 端口
server 127.0.0.1:9611;
}
server
{
listen 80;
server_name xxxxx;
..........
location /{
if ($request_method = 'OPTIONS') {
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Headers X-Requested-With;
add_header Access-Control-Allow-Methods GET,POST,PUT,DELETE,PATCH,OPTIONS;
# 解决假请求问题,如果是简单请求则没有这个问题,但这里是上传文件,首次请求为 OPTIONS 方式,实际请求为 POST 方式
# Provisional headers are shown.
# Request header field Cache-Control is not allowed by Access-Control-Allow-Headers in preflight response.
add_header Access-Control-Allow-Headers 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range,Authorization';
return 200;
}
........
proxy_pass http://a2admin;
}
}
|