命中Node Express端点时URLSession.shared.dataTask数据始终为空

时间:2018-10-25 06:06:32

标签: ios node.js swift swift4 nsurlsession

我有一个简单的Node Express端点,可以用curl成功击中它:

curl --header "Content-Type: application/json" \
  --request POST \
  --data '{"lat":33.485834000000001,"long":-100.106417}' \
  http://192.168.99.100:49160/login
{"status":200,"data":{"userId":"bff37d9c-25a9-421b-aa58-eba0fef0da03"},"message":null}

但是,当我尝试击中相同的端点但在Swift 4中使用以下命令时:

let task = URLSession.shared.dataTask(with: urlRequest) { data, response, error in
            guard let serverData = data, error == nil else {
                handler(ResponseBuilder().set(error: ErrorType.network).build())

                return
            }

           // Process data.
        }
        task.resume()

URLSession返回给我的“数据”中没有任何内容。我希望这些数据包含与上面返回的curl相同的值。

“响应”的填充符合我的预期:

Optional<NSURLResponse>
  - some : <NSHTTPURLResponse: 0x600000a1a5a0> { URL: http://192.168.99.100:49160/login } { Status Code: 200, Headers {
    Connection =     (
        "keep-alive"
    );
    "Content-Length" =     (
        86
    );
    "Content-Type" =     (
        "application/json; charset=utf-8"
    );
    Date =     (
        "Thu, 25 Oct 2018 05:51:39 GMT"
    );
    Etag =     (
        "W/\"56-8ZCdAcNDopMfakzfNDEniZ0fgoc\""
    );
    "X-Powered-By" =     (
        Express
    );
} }

“错误”为零,我正在服务器上登录以表明它已被命中,但数据仍然为空。

我正在使用模拟器运行iOS应用。

我在这里缺少明显的东西吗?

更新1

回答以下一些问题。如下创建“ urlRequest”:

var urlRequest = URLRequest(url: request.url)
urlRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")
urlRequest.addValue("application/json", forHTTPHeaderField: "Accept")
urlRequest.httpMethod = "POST"
urlRequest.httpBody = try? JSONSerialization.data(withJSONObject: request.data, options: .prettyPrinted)

其中“请求”只是我使用的包装对象,其内容为:

Request
  ▿ url : http://192.168.99.100:49160/login
    - _url : http://192.168.99.100:49160/login
  ▿ data : 2 elements
    ▿ 0 : 2 elements
      - key : "lat"
      - value : 33.485834000000001
    ▿ 1 : 2 elements
      - key : "long"
      - value : -100.106417

更新3

有人建议我安装了Charles Proxy。结果如下:

请求:

{
  "lat" : 33.485834000000001,
  "long" : -100.106417
}

响应:

{"status":200,"data":{"userId":"3d559555-c0ad-4e3a-a10b-3e267ee7f662"},"message":null}

1 个答案:

答案 0 :(得分:0)

不幸的答案是,在这种情况下,xcode调试器可能不可靠(URLSession上下文中的完成处理程序)-它始终显示数据为0字节。

使用以下任一方法打印数据:

let received = String(data: data!, encoding: String.Encoding.utf8)
print("\(received)")

let resultObject = try JSONSerialization.jsonObject(with: data!, options: [.allowFragments,])
print("\(resultObject)")

尽量避免过分摇头而伤脖子...