【问题标题】:Custom routes in json-server for nested endpointjson-server 中用于嵌套端点的自定义路由
【发布时间】:2020-04-17 05:13:08
【问题描述】:

为了测试客户端的ApiService 类,我需要用模拟替换我的真实后端 URL,为此我选择了 json-server。我设置了一个代理配置,将所有以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

我做错了什么?

【问题讨论】:

    标签: angular json-server


    【解决方案1】:

    由于我的错误和 json-server 的魔法,我的解决方案不起作用:

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

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

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

    【讨论】:

    • Ты не Шах ты царь!
    • @Spectr ))) Ну, тут я обычно Wax)
    • 不支持嵌套路由很烦人。那么 db.json 将是一个没有嵌套的巨大平面文件,这是故意的吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-25
    • 2014-08-22
    • 1970-01-01
    相关资源
    最近更新 更多