【问题标题】:Alamofire request parameters emptyAlamofire 请求参数为空
【发布时间】:2017-05-08 04:55:15
【问题描述】:

我正在尝试使用 Alarmofire 库发送 POST 请求,但该请求未正确发送参数。

我的代码:

let parameters : Parameters = [
    "email": tfLoginEmail.text! as String,
    "password": tfLoginPassword.text! as String
]
Alamofire.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default).responseJSON{ response in
    //Some code that uses the response
}

参数变量的计数为 2 并且两个值都存在,但对该请求的响应是关于电子邮件和/或密码为空的错误。

编辑: 我的PHP:

/**
 * Account Login
 * url - /login
 * method - POST
 * params - email, password
 */
$app->post('/login', function() use ($app) {
            // check for required params
            verifyRequiredParams(array('email', 'password'));

            // reading post params
            $email = $app->request()->post('email');
            $password = $app->request()->post('password');
            $response = array();

            $db = new DbHandler();
            // check for correct email and password
            if ($db->checkLogin($email, $password)) {
                // get the user by email
                $account = $db->getAccountByEmail($email);

                if ($account != NULL) {
                    $response["error"] = false;
                    $response['id'] = $account['id'];
                    $response['name'] = $account['name'];
                    $response['email'] = $account['email'];
                } else {
                    // unknown error occurred
                    $response['error'] = true;
                    $response['message'] = "An error occurred. Please try again";
                }
            } else {
                // user credentials are wrong
                $response['error'] = true;
                $response['message'] = 'Login failed. Incorrect credentials';
            }
            echoRespnse(200, $response);
        }); 

我想知道我做错了什么。 提前致谢。

【问题讨论】:

  • 你能用它添加服务器代码吗?
  • @ArnaudWurmel 当然,等会
  • @ArnaudWurmel 给你,刚刚添加了它
  • 您需要在请求正文中或作为 URL 参数发送电子邮件和密码吗?
  • 试试encoding: URLEncoding.httpBody而不是encoding: JSONEncoding.default,看看是否有帮助。

标签: php swift alamofire


【解决方案1】:

显然,服务器希望请求正文是 URL 编码的字符串,而不是 JSON。使用encoding: URLEncoding.httpBody 而不是encoding: JSONEncoding.default 来解决此问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-25
    • 2017-02-13
    • 1970-01-01
    • 2017-12-15
    • 1970-01-01
    • 2016-09-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多