json-server 中嵌套端点的自定义路由

Custom routes in json-server for nested endpoint

为了测试客户端的 ApiService class 我需要用模拟替换我的真实后端 URL 并且出于这些目的我选择了 json-服务器。我设置了一个代理配置,将所有以 http://localhost:4200/v1/api 开头的请求转发到 http://localhost:3000:

{
    "/api/v1": {
        "target": "http://localhost:3000",
        "secure": false
    }
}

当我发送 http://localhost:4200/api/v1/users BUT 之类的请求时它会起作用,但不适用于嵌套端点(例如 http://localhost:4200/api/v1/auth/token)。我发现 json-server 不支持对嵌套对象的请求,所以我更改了 data.json 如下:

{
    "auth_token": {
        "access_token":"accesstoken1",
        "token_type":"Bearer"
    }
}

并为 json-server 设置 routes.json:

{
    "/auth/token": "/auth_token"
}

但它仍然无法通过 json-server 使用 routes.json:

[0]   Other routes
[0]   /auth/token -> /auth_token

我做错了什么?

由于我的错误和 json-server 的魔法,我的解决方案没有奏效:

我发现 json-server 自动将 /api/v1 替换为 /。但是,如果您使用上面的路由设置,则 /api/v1/auth/token 不会自动替换为 /api/v1/auth_token,您将收到 404 错误。

所以 json-server 行为给我造成了一种错觉,即 Angular 中的代理设置替换了http://localhost:4200/api/v1http://localhost:3000。因此,在我的案例中,正确的路由如下所示:

{
    "/api/v1/auth/token": "/api/v1/auth_token"
}