2016-12-22 175 views
4

我試圖用Alarmofire庫發送POST請求,但請求沒有正確發送參數。Alamofire請求參數爲空

我的代碼:

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); 
     }); 

我想知道我在做什麼錯。 在此先感謝。

+0

你可以添加服務器代碼嗎? –

+0

@ArnaudWurmel當然,在一瞬間 –

+0

@ArnaudWurmel在這裏,你去,只是添加它 –

回答

6

顯然,服務器期望請求主體是一個URL編碼的字符串,而不是JSON。使用encoding: URLEncoding.httpBody而不是encoding: JSONEncoding.default來解決此問題。