未能在 Vapor 路由中呼叫第 3 方 API

Failing To Call 3rd Party API in Vapor Route

当客户使用 Swift 和 Vapor 3 前往特定路线时,我正在尝试呼叫第 3 方 API;然而,尽管能够拨打电话,我还是遇到了错误。

我已采取措施确保错误是由 API 的获取请求引起的。目前,除了打​​印响应外,我对请求不做任何事情。删除请求会阻止错误发生。

// Route the user to HomePage
router.get { req -> Future<View> in
    let token: String = "THATS_MY_TOKEN"
    let client = try req.client()
    let bcmsrequest = try client.get("https://api.buttercms.com/v2/posts/?page=1&page_size=10&auth_token=" + token)
    print(bcmsrequest)
    print("This line prints.")
    // Removing the above get request stops the error below from happening
    return try req.view().render("welcome")
}

// Here is the stdout printed by the server process:
Server starting on http://localhost:8080
NIO.EventLoopFuture<Vapor.Response>
This line prints.
2019-07-27 11:49:12.249196-0400 Run[6348:121267] [] nw_endpoint_get_type called with null endpoint
2019-07-27 11:49:12.249420-0400 Run[6348:121267] [] nw_endpoint_get_type called with null endpoint, dumping backtrace:
        [x86_64] libnetcore-1872
    0   libnetwork.dylib                    0x00007fff6d188fc8 __nw_create_backtrace_string + 120
    1   libnetwork.dylib                    0x00007fff6ce12af4 nw_endpoint_get_type + 180
    2   libboringssl.dylib                  0x00007fff6b6e3af2 nw_protocol_boringssl_get_subject_name + 178
    3   libboringssl.dylib                  0x00007fff6b6e6997 nw_protocol_boringssl_connected + 916
    4   libnetwork.dylib                    0x00007fff6ce5d145 nw_socket_handle_socket_event + 1733
    5   libdispatch.dylib                   0x00000001017fd82f _dispatch_client_callout + 8
    6   libdispatch.dylib                   0x0000000101800689 _dispatch_continuation_pop + 585
    7   libdispatch.dylib                   0x0000000101816608 _dispatch_source_invoke + 2135
    8   libdispatch.dylib                   0x0000000101807665 _dispatch_workloop_invoke + 3477
    9   libdispatch.dylib                   0x0000000101813025 _dispatch_workloop_worker_thread + 676
    10  libsystem_pthread.dylib             0x000000010188f343 _pthread_wqthread.cold.1 + 125
    11  libsystem_pthread.dylib             0x0000000101889196 _pthread_wqthread + 203
    12  libsystem_pthread.dylib             0x0000000101889057 start_wqthread + 15

我可以看到正在打印一个 Future 对象,我希望看到响应内容(一个 JSON 字符串)- 但我认为该响应没有内容并且实际上未能生成完全没有要求。

I can see that a Future Object is being printed out, I would expect to see response content

所以这就是问题的症结所在。因为 Vapor 是异步的,所以一旦 发送请求,您就会打印 Future<Response> ,这意味着它还没有返回。如果将其更改为:

router.get { req -> Future<View> in
    let token: String = "THATS_MY_TOKEN"
    let client = try req.client()
    let bcmsrequest = try client.get("https://api.buttercms.com/v2/posts/?page=1&page_size=10&auth_token=" + token)
    return bcmsrequest.flatMap { response in
        print(response)
        return try req.view().render("welcome")
    }
}

您将看到完整的响应正文并查看您遇到的错误(如果有)