跨域路由 重写路由类addRoute 解决添加路由繁琐问题

来者可追

之前由于没好好看文档,在跨域处理上浪费了不少时间。
截图

因为我是自定义路由的,又想使用标准restful api 路由,所以使用resource 配置起来比较方便,但是我发现加了跨域中间件后,就不能使用resource路由了。

另外由于为了不暴露某些路由 我不想使用any方法,因此每次都得addRoute 中 参数加一个OPTIONS ,比较麻烦。

因此今天重写了一些路由类中的addRoute方法

代码如下

<?php

namespace support;

use Webman\Route\Route as RouteObject;

class Route extends \Webman\Route
{

    public static function addRoute($methods, string $path, $callback): RouteObject
    {
        // 针对 resource 路由 会重复addRoute 要保证最终methods 中只含有一个 OPTIONS
        // 因此需要判断当前路由的methods中是否存在OPTIONS
        $routes = static::getRoutes();
        $has_options = false;
        foreach ($routes as $route) {
            if ($route->getPath() == $path && in_array('OPTIONS', $route->getMethods())) {
                $has_options = true;
                break;
            }
        }
        if (!$has_options) {
            // 针对只添加一次的路由,自动添加OPTIONS请求
            $methods = is_array($methods) ? $methods : [$methods];
            if (!in_array('OPTIONS', $methods)) {
                $methods[] = 'OPTIONS';
            }
        }

        return parent::addRoute($methods, $path, $callback); // TODO: Change the autogenerated stub
    }
}

目前测试一切ok~ 有同样需求的可以copy一下,逻辑也比较简单。

这样定义路由的时候,直接按照get post put 等方法配置就可以了,resource 测试也是ok的!

515 0 0
0个评论

来者可追

320
积分
0
获赞数
0
粉丝数
2023-06-16 加入
🔝