【问题标题】:Trouble passing json data from Swift to Node.js将 json 数据从 Swift 传递到 Node.js 时遇到问题
【发布时间】:2021-11-15 03:51:46
【问题描述】:

我正在尝试在 Swift 中提供我的 URL 发布请求正文。在 Swift 方面,一切似乎都运行良好,但我在 Node.js 中没有看到它。

创建 URL 的 Swift 函数:

func composeURL_Request(path: String, queryDict: [String:String], method: String? = nil, body: [String: Any]? = nil) -> URLRequest {
    var components = URLComponents()

    components.scheme = "http"
    components.host = "localhost"
    components.port = 4001

    components.path = path
    components.setQueryItems(with: queryDict)

    var request = URLRequest(url: components.url!)

    // optional components
    if !(method == nil) {
        request.httpMethod = method
    }

    if !(body == nil) {

        do {
            let jsonData = try JSONSerialization.data(withJSONObject: body!, options: .prettyPrinted)
            request.httpBody = jsonData
        } catch {
            print(error.localizedDescription)
        }
    }

    return request
}

此函数不会打印catch 中的任何内容,所以我认为它工作正常。

然后使用 Node.js,我能够打印出正确的查询参数,但打印出正文输出 {}。 Node.js 代码:

app.post("/host", (req, res) => {
    const userID = req.query.userID;
    const eventID = req.query.eventID;
    const body = req.body;
    console.log(userID)
    console.log(eventID)
    console.log(body)
})

编辑:

下面是调用 Swift 函数的代码:

let url = composeURL_Request(path: "/host",
                         queryDict: ["userID": 
"erIIm5g5uQToAioCiKnOhP1griR2", "eventID": "eventID_001"],
                         method: "POST",
                         body: ["invited": 
["Ax8Fx44T1sZAHUiTwyHRANqJOm43"],
                                "description": "long event 
description. long event description. long event description",
                                "date": 1636943919175,
                                "includes image": false])

不幸的是,它看起来一团糟。

【问题讨论】:

  • 什么是jsonData打印? JSONSerialization 显然没有失败,而是返回了一个空对象。
  • 没有任何打印错误,但是打印成功的json序列化输出“204字节”

标签: node.js json swift


【解决方案1】:

问题是我需要指定我的URLRequest 的内容类型,以便Express 不会忽略它。

将此代码放入构成 URLRequest 的函数中可以解决默认 JSON 解析器 (app.use(express.json()) 的问题:

request.setValue("application/json", forHTTPHeaderField: "Content-Type")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-28
    • 1970-01-01
    • 1970-01-01
    • 2013-12-16
    相关资源
    最近更新 更多