webman常见问题
# 跨域
namespace app\middleware;
use Webman\Http\Request;
use Webman\Http\Response;
use Webman\MiddlewareInterface;
/**
* 跨域请求中间件
*/
class AccessControl implements MiddlewareInterface
{
public function process(Request $request, callable $handler): Response
{
// 处理 OPTIONS 预检请求
if ($request->method() === 'OPTIONS') {
$response = response('', 204); // 204 No Content
} else {
$response = $handler($request);
}
// 获取请求来源
$origin = $request->header('origin', '*');
// 允许的域名列表,可以根据需要配置
// $allowed_origins = [
// 'http://localhost:8080',
// 'http://127.0.0.1:8080',
// 'http://localhost:3000',
// 'http://127.0.0.1:3000',
// // 添加其他允许的域名
// ];
// 检查来源是否在允许列表中,如果在则设置具体的origin,否则设置为*
// $allow_origin = in_array($origin, $allowed_origins) ? $origin : '*';
// 设置 CORS 头
$response->header('Access-Control-Allow-Origin', $origin);
$response->header('Access-Control-Allow-Credentials', 'true');
$response->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS');
$response->header('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With, Accept, Origin');
$response->header('Access-Control-Max-Age', '3600');
// 暴露给浏览器的头信息(如果需要的话)
$response->header('Access-Control-Expose-Headers', 'Content-Length, Content-Range');
return $response;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
全局跨域配置config/middleware.php
return [
'' => [
app\middleware\AccessControl::class, // 跨域
]
];
1
2
3
4
5
2
3
4
5
上次更新: 2026/06/05, 13:59:19