简体   繁体   English

Alamofire 表单编码的 POST 请求因 responseSerializationFailed 而失败

[英]Alamofire Form Encoded POST Request Failing with responseSerializationFailed

Making a request with Alamofire (swift 4) to an api endpoint (form encoded content type) and passing a username and password via login.使用 Alamofire (swift 4) 向 api 端点(表单编码的内容类型)发出请求,并通过登录传递用户名和密码。 When testing in POSTMAN, this endpoint works without errors and returns valid JSON (see below).在 POSTMAN 中进行测试时,此端点正常工作并返回有效的 JSON(见下文)。

在此处输入图片说明

My swift code is as follows:我的快速代码如下:

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

The response I get is as follows:我得到的回应如下:

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

Any insight would be appreciated!任何见解将不胜感激!

Change JSONEncoding.default to URLEncoding.default as below,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)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM