我正在制作一个注册系统(获取用户信息,如姓名,电子邮件),使用Swift作为前端,php作为后端,mysql作为数据库。 (使用我自己的服务器,而不是localhost)并尝试从Swift发送HTTP post请求以将数据插入用户表。(mySQL)。我使用的是安全的https网址。
问题是,当我尝试传递数据(名字,姓氏,电子邮件,密码)时,我总是得到一个错误的请求(400)“缺少必需的信息”,如截图,不能让用户注册...... enter image description here
如果我可以传递数据,我应该得到成功回复(200)“注册成功”。 php中的函数被调用,所以我假设我的PHP代码没有错,但是Swift代码。
我想知道为什么我无法将数据传递到我的服务器(可能来自MySQL设置?)。 在此先感谢您的编码!
我的php文件(文件名:registerUser.php):
<?php
require("Conn.php");
require("MySQLDAO.php");
$returnValue = array();
if(empty($_REQUEST["userEmail"]) || empty($_REQUEST["userPassword"]) || empty($_REQUEST["userFirstName"]) || empty($_REQUEST["userLastName"]))
{
$returnValue["status"]="400";
$returnValue["message"]="Missing required information";
echo json_encode($returnValue);
return;
}
$userEmail = htmlentities($_REQUEST["userEmail"]);
$userPassword = htmlentities($_REQUEST["userPassword"]);
$userFirstName = htmlentities($_REQUEST["userFirstName"]);
$userLastName = htmlentities($_REQUEST["userLastName"]);
//generate secured passowrd
$salt = openssl_random_pseudo/bytes(16);
$secured_password = sha1($userPassword . $salt);
$dao = new MySQLDAO(Conn::$dbhost, Conn::$dbuser, Conn::$dbpassword, Conn::$dbname);
$dao->openConnection();
//check if user with provided username is available
$userDetails = $dao->getUserDetails($userEmail);
if (!empty($userDetails))
{
$returnValue["status"]="400";
$returnValue["message"]="Please choose a different email address";
echo json_encode($returnValue);
return;
}
//Register new User
$result = $dao->registerUser($userEmail, $userFirstName, $userLastName, $secured_password, $salt);
if($result){
$userDetails = $dao->getUserDetails($userEmail);
$returnValue["status"] = "200";
$returnValue["message"] = "Registration successful";
$returnValue["userId"] = $userDetails["user_id"];
$returnValue["userFirstName"] = $userDetails["first_name"];
$returnValue["userLastName"] = $userDetails["last_name"];
$returnValue["userEmail"] = $userDetails["email"];
} else {
$returnValue["status"]="400";
$returnValue["message"]="Couldn't register";
}
$dao->closeConnection();
echo json_encode($returnValue);
?>
我的Swift代码:
lazy var submitButton: UIButton = {
let button = UIButton(type: .system)
button.backgroundColor = UIColor(red:0.09, green:0.51, blue:0.92, alpha:1.0)
button.translatesAutoresizingMaskIntoConstraints = false
button.setTitle("Signup", for: .normal)
button.setTitleColor(.white, for: .normal)
button.addTarget(self, action: #selector(handleSubmit), for: .touchUpInside)
return button
}()
func handleSubmit() {
guard let userFirstName = userFirstNameTextField.text, let userLastName = userLastNameTextField.text, let userEmail = emailTextField.text, let userPassword = passwordTextField.text, let repeatPassword = repeatPasswordTextField.text
else {
print("Form is not valid")
return
}
if (userPassword != repeatPassword) {
self.displayAlertMessage(userMessage: "Passwords do not match")
return
}
if (userFirstName.isEmpty || userLastName.isEmpty || userEmail.isEmpty || userPassword.isEmpty) {
self.displayAlertMessage(userMessage: "All fields are required")
return
}
let myUrl = NSURL(string: "https://my URL name/registerUser.php")
let request = NSMutableURLRequest(url: myUrl! as URL)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let postString = "userEmail=\(userEmail)&userFirstName=\(userFirstName)&userLastName=\(userLastName)&userPassword=\(userPassword)"
request.httpBody = postString.data(using: String.Encoding.utf8)
let task = URLSession.shared.dataTask(with: request as URLRequest) {(data:Data?, response:URLResponse?, error: Error?) -> Void in
DispatchQueue.main.async {
if error != nil {
self.displayAlertMessage(userMessage: "Error")
return
}
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
if let parseJSON = json {
let userId = parseJSON["userId"] as? String
if (userId != nil) {
let myAlert = UIAlertController(title: "Success", message: "Registration Successful", preferredStyle: UIAlertControllerStyle.alert)
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)
myAlert.addAction(okAction)
self.present(myAlert, animated: true, completion: nil)
} else {
print(123)
let errorMessage = parseJSON["message"] as? String
if (errorMessage != nil) {
self.displayAlertMessage(userMessage: errorMessage!)
}
}
}
} catch {
print(error)
}
}
}
task.resume()
}
答案 0 :(得分:0)
由于您收到400错误&#34;缺少所需信息&#34;它不是能够将信息存储在数据库中而是从POST请求中获取值的问题(由此行触发):
if(empty($ _ REQUEST [&#34; userEmail&#34;])|| empty($ _ REQUEST [&#34; userPassword&#34;])|| empty($ _ REQUEST [&#34; userFirstName&# 34;])|| empty($ _ REQUEST [&#34; userLastName&#34;])))
我首先打印出这些值。他们中的任何一个出现了吗?只有一个空吗?如果它们都是空的,那么问题就是你如何从前端发送参数。