【发布时间】:2019-07-08 23:08:38
【问题描述】:
我正在尝试实现 Swift 前端,以便它可以将数据上传到数据库,该数据库是通过 Flask 用 Python 编写并利用 PostgreSQL。我用于发送 POST 请求的前端 Swift 代码目前如下,如果重要的话,它是在 View Controller 中编写的:
func PostData(){
let parameters:[String: Any]=["latitude": 35.0094040,
"longitude": -85.3275640,
"tag": "this is my fancy tag",
"image":"icecream.jpg"]
let jsonURLString="http://localhost/api/tags"
guard let url=URL(string: jsonURLString) else{
return
}
var request=URLRequest(url: url)
request.httpMethod="POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
guard let httpBody=try? JSONSerialization.data(withJSONObject: parameters, options: []) else{
return
}
request.httpBody=httpBody
let session=URLSession.shared
session.dataTask(with: request) { (data, _, error) in
if let data=data{
do{
try JSONSerialization.jsonObject(with: data, options: [])
}catch{
print(error)
}
}
}.resume()
}
我接受post请求的后端代码如下:
@app.route('/api/tags', methods= ["GET", "POST"])
def get_tags_api():
if request.method == "POST":
latitude = request.form.get("latitude")
longitude = request.form.get("longitude")
text = request.form.get("tag")
image_ = request.form.get("image", None)
print (latitude)
print (longitude)
print (text)
print (image_)
create_tags(latitude=latitude, longitude=longitude, text=text, image=image_)
当我尝试运行以下代码时,我最终收到了来自 Xcode 的以下错误消息:
Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}
在后端,所有变量都打印为 None,并带有以下错误消息:
[SQL: INSERT INTO tags (text, longitude, latitude, image) VALUES (%(text)s, %(longitude)s, %(latitude)s, %(image)s) RETURNING tags.id]
[parameters: {'text': None, 'longitude': None, 'latitude': None, 'image': None}]
(Background on this error at: http://sqlalche.me/e/gkpj)
鉴于前端PostData函数运行时后端显示错误消息,请求肯定已经发送,但后端没有从请求中检测到任何数据,我不知道这是为什么。我不确定我在这里做错了什么。我对 Swift 比较陌生,而且我对 Flask 没有太多经验。请帮忙。
【问题讨论】: