Swift/MySQL/PHP“缺少必需参数”错误

Posted

技术标签:

【中文标题】Swift/MySQL/PHP“缺少必需参数”错误【英文标题】:Swift/MySQL/PHP 'Required Parameters Missing' Error 【发布时间】:2017-11-14 05:47:17 【问题描述】:

这是我注册用户的快捷方式:

//Information fields
@IBOutlet weak var user: UITextField!
@IBOutlet weak var pass: UITextField!
@IBOutlet weak var pass2: UITextField!
@IBOutlet weak var name: UITextField!
@IBOutlet weak var email: UITextField!
@IBOutlet weak var Message: UILabel!


//Register button
@IBAction func register(_ sender: Any) 

    let Parameters = ["username": user.text, "password": pass.text, "email": email.text, "name": name.text]

    let url = URL(string: "http://cgi.soic.indiana.edu/~lvweiss/prof4/register.php")!

    let session = URLSession.shared

    var request = URLRequest(url: url)
    request.httpMethod = "POST"

    do 
        request.httpBody = try JSONSerialization.data(withJSONObject: Parameters, options: .prettyPrinted)
     catch let error 
        print(error.localizedDescription)
        Message.text = String(error.localizedDescription)
    

    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")

    let task = session.dataTask(with: request as URLRequest, completionHandler:  data, response, error in

        guard error == nil else 
            return
        

        guard let data = data else 
            return
        

        do 
            if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] 
                print(json)
                
         catch let error 
            print(error.localizedDescription)
            self.Message.text = String(error.localizedDescription)
        
    )
    task.resume()


override func viewDidLoad() 
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.


override func didReceiveMemoryWarning() 
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.

这里是 PHP:

<?php
require_once 'DbOperation.php';

$response = array();

if ($_SERVER['REQUEST_METHOD'] == 'POST') 
if (!verifyRequiredParams(array('username', 'password', 'email', 'name'))) 
    //getting values
    $username = $_POST['username'];
    $password = $_POST['password'];
    $email = $_POST['email'];
    $name = $_POST['name'];

    //creating db operation object
    $db = new DbOperation();

    //adding user to database
    $result = $db->createUser($username, $password, $email, $name);

    //making the response accordingly
    if ($result == USER_CREATED) 
        $response['error'] = false;
        $response['message'] = 'User created successfully';
     elseif ($result == USER_ALREADY_EXIST) 
        $response['error'] = true;
        $response['message'] = 'User already exist';
     elseif ($result == USER_NOT_CREATED) 
        $response['error'] = true;
        $response['message'] = 'Some error occurred';
    
 else 
    $response['error'] = true;
    $response['message'] = 'Required parameters are missing';

 else 
$response['error'] = true;
$response['message'] = 'Invalid request';


//function to validate the required parameter in request
function verifyRequiredParams($required_fields)


//Looping through all the parameters
foreach ($required_fields as $field) 
    //if any requred parameter is missing
    if (!isset($_POST[$field]) || strlen(trim($_POST[$field])) <= 0) 

        //returning true;
        return true;
    

return false;


echo json_encode($response);
?>

这是我要发布到数据库的信息: ios 注册字段:

点击注册按钮时我从 Xcode 收到的错误:

2017-11-14 00:42:01.529344-0500 WeissProf4[8754:662299] [MC] 延迟加载 NSBundle MobileCoreServices.framework 2017-11-14 00:42:01.530670-0500 WeissProf4[8754:662299] [MC] 加载 MobileCoreServices.framework 2017-11-14 00:42:01.550941-0500 WeissProf4[8754:662299] [MC] systemgroup.com.apple.configurationprofiles 路径的系统组容器是 /Users/leviweiss/Library/Developer/CoreSimulator/Devices/C98EE410-1CA2 -4B4B-9ED8-A4F112C629E2/data/Containers/Shared/SystemGroup/systemgroup.com.apple.configurationprofiles 2017-11-14 00:42:03.468653-0500 WeissProf4[8754:662299] [MC] 从私人有效用户设置中读取。 2017-11-14 00:42:04.769899-0500 WeissProf4[8754:662505] [MC] 缓存无效 2017-11-14 00:42:05.281372-0500 WeissProf4[8754:662299] [MC] 从私人有效用户设置中读取。 [“消息”:缺少必需的参数,“错误”:1]

我不确定发生了什么,我知道 PHP 已成功连接到数据库并且能够发布所需的信息(使用 Postman 测试)。我认为 Swift 如何处理 PHP 中的发布可能是一个错误,尽管我绝对不是 PHP 专家。

【问题讨论】:

如果它与 Postman 一起使用,那么它只是您的 Swift 代码没有正确发布参数。尝试在 PHP 代码中添加 var_dump($_POST) 并检查 Swift 实际发布的内容。 实际上,看起来您在正文中发布了一个 json 字符串,而不是使用“普通”www-form(发布数据,如param1=value1&amp;param2=value2&amp;...)。如果在正文中发布 json 字符串,则需要提取字符串并在 PHP 中手动解析。检查这个问题的答案:***.com/questions/37400639/… 感谢您指出这一点,效果很好!在 Swift 4 中添加了对解决方案的编辑。 将其添加为答案。这样你就可以接受它,让其他人知道问题已经解决,并且更容易让未来的访问者找到。 【参考方案1】:

解决方案 Swift4:

@IBAction func register(_ sender: Any) 

let request = NSMutableURLRequest(url: NSURL(string: "http://cgi.soic.indiana.edu/~lvweiss/prof4/register.php")! as URL)
request.httpMethod = "POST"
let postString = "username=\(user.text!)&password=\(pass.text!)&email=\(email.text!)&name=\(name.text!)"
request.httpBody = postString.data(using: String.Encoding.utf8)

let task = URLSession.shared.dataTask(with: request as URLRequest) 
    data, response, error in

    if error != nil 
        print("error=\(String(describing: error))")
        return
    

    print("response = \(String(describing: response))")

    let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
    print("responseString = \(String(describing: responseString))")

task.resume()

【讨论】:

以上是关于Swift/MySQL/PHP“缺少必需参数”错误的主要内容,如果未能解决你的问题,请参考以下文章

缺少必需参数:refresh_token 节点 js

错误:invalid_request 缺少必需参数:golang 中的 client_id

获取缺少必需参数:范围 Passport.js,快递

对缺少必需参数的应用商店做出本机反应

使用 Google Apps 脚本将查询中的数据加载到 Big Query - 缺少必需参数

Swift/MySql/PHP - “无法读取数据,因为它的格式不正确。”错误