Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alamofire request parameters empty

I'm trying to send a POST request with the Alarmofire library, but the request doesn't send the parameters properly.

My Code:

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
}

The parameters variable has a count of 2 and both values are present, but the response to this request is an error about email and/or password being empty.

EDIT: My 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);
        }); 

I'd like to know what I'm doing wrong. Thanks in advance.

like image 783
Dennis van Opstal Avatar asked Dec 22 '16 14:12

Dennis van Opstal


1 Answers

Apparently the server expects the request body to be a URL-encoded string, not a JSON. Use encoding: URLEncoding.httpBody instead of encoding: JSONEncoding.default to fix this issue.

like image 136
Andrii Chernenko Avatar answered Sep 25 '22 08:09

Andrii Chernenko