我收到一个令人困惑的错误。 它与 swift 数据类型有关。 这是我的网络演示:
func initRequst(HttpType: httpType,content:String,dic:Dictionary<String,Any>){
let data = try! JSONSerialization.data(withJSONObject: dic, options: .prettyPrinted)
print(data)
switch HttpType {
case .post:
url = URL.init(string: "http://localhost:5000/" + content)
req = NSMutableURLRequest.init(url: url!)
req?.httpMethod = "POST"
req?.httpBody = data
case .get:
url = URL.init(string: "http://localhost:5000/" + content)
req = NSMutableURLRequest.init(url: url!)
req?.httpBody = data
req?.httpMethod = "GET"
}
}
这是我的 Flask 服务器收到错误和演示:
TypeError: 'NoneType' object is not subscriptable
@app.route('/userLogin',methods=["GET"])
def userLogin():
get_username = request.json['username']
get_password = request.json['password']
return jsonify({"uerId":databasePort.checkUserInformation(get_username,get_password)})
似乎没有识别swift数据发送类型,如何解决?谢谢!
最佳答案
您可以尝试在 Swift 中发送请求之前将 Content-Type
header 设置为 application/json
。然后 Flask 将尝试对其进行解码并将其分配给请求的 json
属性:
req.setValue("application/json", forHTTPHeaderField: "Content-Type")
仅当传入请求将内容类型设置为 json 时,Flask 才会设置 request.json
,否则它将采用表单编码数据并将其分配给 request.form
.
关于python - 错误:how to fix the swift error type to my server,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42454150/