swift - 在 Vapor Route 中调用 3rd 方 API 失败
问题描述
当客户端使用 Swift 和 Vapor 3 转到特定路线时,我正在尝试调用第 3 方 API;但是,尽管能够拨打电话,我还是遇到了错误。
我已采取措施确保错误是由对 API 的 get 请求引起的。目前,除了打印响应之外,我对请求什么都不做。删除请求会阻止错误发生。
// 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
我可以看到正在打印出一个未来对象,我希望看到响应内容(一个 JSON 字符串)——但我相信响应没有内容,实际上根本没有发出请求。
解决方案
我可以看到正在打印出未来对象,我希望看到响应内容
所以这是问题的症结所在。因为 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")
}
}
您将看到完整的响应正文并查看您遇到的错误(如果有)
推荐阅读
- r - 正确创建和读取具有多种语言的特定字符的 .csv 文件
- storage - 防止 H2O 写入 tmp 文件
- ms-word - 动态修改交叉引用工具提示文本
- linux - 使用 POSIX 消息队列进行进程内通信
- java - 如何将嵌套的 JSON 输入发送到 Java 中的 RESTful Web 服务?
- c - 为什么在文件结束指示器被清除后不提示用户输入?
- java - 将一个庞大的循环分解为多种方法?
- python - 如何在正则表达式的括号中获取分号
- python - 在 Shopify 中按变体 SKU 更新库存
- database - 无论我使用 --dbpath,MongoDB 都在访问相同的数据,这正常吗?