向s发出post请求时出现Json错误

2024-03-29 05:24:24 发布

您现在位置:Python中文网/ 问答频道 /正文

经过几个小时的搜索和复习,我仍然不能让这个工作。请帮我指引方向!你知道吗

我所要做的是提交一个用户名到我的服务器,并保存在MySQL中-只是为了让它工作。。。你知道吗

我可以将用户名发送到服务器,甚至将硬编码的数据返回到iOS模拟器以设置标签的文本,但是一旦我添加了将数据保存到MySQL的功能,我得到错误:“error Domain=nscococaerordomain Code=3840”字符0周围的值无效。“UserInfo={NSDebugDescription=Invalid value around character 0.}”

抱歉奇怪的命名惯例,我偏离了我以前的教程跟踪。谢谢你!你知道吗

SWIFT 3:

func Apitest(name: String) {

    let json = ["user" : name]

    do {
        let jsonData = try JSONSerialization.data(withJSONObject: json, options: .prettyPrinted)

        let url = NSURL(string: "I put the actual path here, don't worry")!
        let request = NSMutableURLRequest(url: url as URL)
        request.httpMethod = "POST"

        request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
        request.httpBody = jsonData

        let task = URLSession.shared.dataTask(with: request as URLRequest){ data, response, error in
            if error != nil{
                print("First Error -> \(error)")
                return
            }
            do {
                let result = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:AnyObject]
                print("Result -> \(result!)")

                let label = result?["messages"] as! String

                print(label)

                self.setupLabel(text: label)

            } catch {
                print("Second Error -> \(error)")
            }
        }

        task.resume()
    } catch {
        print(error)
    }
}

API代码(python/flask)

@app.route('/api/get_messages/') methods=['POST'])
def get_messages():
json = request.get_json()

api_test(json['user'])

return jsonify({'messages':json['user']})

MySQL函数:

def api_test(user):
c, conn = connection()
c.execute("INSERT INTO users (email) VALUES (%s)", (user))
conn.commit()
conn.close()
c.close()

Tags: apijsonurldatastringrequestasmysql