Mrcdh技术博客 Mrcdh技术博客
首页
  • Html5
  • Javascript
  • Nodejs
  • electron
  • Android
  • 微信公众号
  • 框架
  • 其他
  • Mysql
  • PHP
  • Python
  • java
  • Gulp
  • 其它
  • 网站
  • 分类
  • 标签
  • 归档
个人产品
GitHub (opens new window)

Mrcdh

全栈开发小学生
首页
  • Html5
  • Javascript
  • Nodejs
  • electron
  • Android
  • 微信公众号
  • 框架
  • 其他
  • Mysql
  • PHP
  • Python
  • java
  • Gulp
  • 其它
  • 网站
  • 分类
  • 标签
  • 归档
个人产品
GitHub (opens new window)
  • ThinkPHP

  • webman

    • webman中的网络请求
    • webman常见问题
      • 跨域
  • FastAdmin

  • laravel

  • laravel-jetstream.vue

  • laravel常用扩展包

  • 《PHP框架》
  • webman
mrcdh
2026-06-05
目录

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

全局跨域配置config/middleware.php

return [
    '' => [
        app\middleware\AccessControl::class, // 跨域
    ]
];
1
2
3
4
5
#webman
上次更新: 2026/06/05, 13:59:19
webman中的网络请求
Fastadmin生成树型结构

← webman中的网络请求 Fastadmin生成树型结构→

最近更新
01
utools开发常见问题
07-13
02
开发规范
04-03
03
webman中的网络请求
03-25
更多文章>
Theme by Vdoing | Copyright © 2020-2026 Mrcdh | 苏ICP备2020058908号-1
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式
×