python - 错误:how to fix the swift error type to my server

标签 python swift

我收到一个令人困惑的错误。 它与 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/

相关文章:

python - NCO 下载 Python

python - 使用 Python,我如何验证英国邮政编码?

python - 无法按分类列过滤 pandas 数据框

Python-Requests 验证参数如何工作? SSL 证书

ios - 获取多行的 UILabel 的垂直尺寸?

swift - ViewController 类没有初始化器

iOS swift : Set video preview

ios - 我怎样才能快速洗牌 RLMResults ?

Python argparse 条件要求

ios - 如何为此日期格式化 NSDateFormatter