Alamofire query parameters are empty

I am trying to send a POST request using the Alarmofire library, but the request does not send the parameters properly.

My code is:

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 parameter variable has a counter of 2 and both values ​​are present, but the answer to this request is an error that the mail and / or password are 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 would like to know what I am doing wrong. Thanks in advance.

+4
source share
1 answer

Apparently, the server expects the request body to be a string encoded by the URL, not JSON. Use encoding: URLEncoding.httpBodyinstead encoding: JSONEncoding.defaultto fix this problem.

+6
source

Source: https://habr.com/ru/post/1664576/


All Articles