Alamofire表单编码POST请求失败,返回responseSerializationFailed

问题描述 投票:1回答:1

向Alamofire(swift 4)发出请求到api端点(表单编码内容类型)并通过登录传递用户名和密码。在POSTMAN中进行测试时,此端点可以正常工作并返回有效的JSON(参见下文)。

enter image description here

我的快捷代码如下:

let headers = [
  "content-type": "application/x-www-form-urlencoded",
   "cache-control": "no-cache"
 ]
let parameters = [
   "username": "[email protected]", 
   "password": "password"
 ]
 Alamofire.request("https://xxxxx.com/api/login/", method: .post, parameters: parameters, encoding:  JSONEncoding.default, headers: headers).responseJSON { response in
   print(response)
 }

我得到的回应如下:

FAILURE: responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}))

任何见解将不胜感激!

swift alamofire
1个回答
1
投票

JSONEncoding.default更改为URLEncoding.default,如下所示,

Alamofire.request("https://xxxxx.com/api/login/", method: .post, parameters: parameters, encoding:  URLEncoding.default, headers: headers).responseJSON { response in
   print(response)
}
© www.soinside.com 2019 - 2024. All rights reserved.