我正在尝试实现 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 没有太多经验。请帮忙。
最佳答案
我认为你的代码是错误的。
guard let httpBody=try? JSONSerialization.data(withJSONObject: parameters, options: []) else {
return
}
关于ios - 来自 swift 前端的 POST 请求问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56943509/