Alamofire请求参数为空

时间:2016-12-22 14:21:26

标签: php swift alamofire

我正在尝试使用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);
        }); 

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

1 个答案:

答案 0 :(得分:10)

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