【问题标题】:Send post request from Swift 4 to Node.js从 Swift 4 向 Node.js 发送 post 请求
【发布时间】:2017-11-08 15:12:28
【问题描述】:

大家好,我在从 Swift 4 向 node.js 服务器发送带有 post 请求的值时遇到问题(我在下面输入代码),以及 node.js 快速使用,在 xcode 上我看到以下错误:不可连接至服务器。我在本地主机上使用 node.js 进行了测试,有人可以帮助我吗?谢谢。

Swift 函数:

@IBAction func LoginFunction(_ sender: Any) {

    // prepare json data
    let json: [String: Any] = ["title": "ABC",
                               "dict": ["1":"First", "2":"Second"]]

    let jsonData = try? JSONSerialization.data(withJSONObject: json)

    // create post request
    let url = URL(string: "http://localhost:3000/login")!
    var request = URLRequest(url: url)
    request.httpMethod = "POST"

    // insert json data to the request
    request.httpBody = jsonData

    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        guard let data = data, error == nil else {
            print(error?.localizedDescription ?? "No data")
            return
        }
        let responseJSON = try? JSONSerialization.jsonObject(with: data, options: [])
        if let responseJSON = responseJSON as? [String: Any] {
            print(responseJSON)
        }
    }

    task.resume()


}

服务器 Node.js

'use strict'

const express = require('express')
const bodyParser = require('body-parser')

// Create a new instance of express
const app = express()

// Tell express to use the body-parser middleware and to not parse extended bodies
app.use(bodyParser.urlencoded({ extended: false }))

// Route that receives a POST request to /sms
app.post('/login', function (req, res) {
  const body = req.body.Body
  res.set('Content-Type', 'text/plain')
  res.send(`You sent: ${body} to Express`)
})

// Tell our app to listen on port 3000
app.listen(3000, function (err) {
  if (err) {
    throw err
  }

  console.log('Server started on port 3000')
})

【问题讨论】:

  • @FrancescoDeliro 是的,我已经尝试过,但它不起作用
  • 您是否在您的 plist 文件中设置了允许任意加载?你的服务器在运行吗?默认情况下不允许非 https 流量,您需要在 plist 中设置此项以允许 http 流量
  • @Scriptable 是的,我已经设置好了,我的服务器运行正常

标签: javascript ios node.js swift express


【解决方案1】:

首先,这取决于您是在设备上运行还是在模拟器上运行。 如果你在设备上运行,你无法通过localhost访问你的服务器,因为localhost指向设备,你只能在模拟器上运行时使用localhost;在设备上运行时,您应该指定计算机的私有 IP。 这是一个快速的 shell 方法,可以打印和复制你的 ip:

ifconfig en0 | awk '/inet.[0-9]/ {print  "\033[1m \033[31m"$2 }' && ifconfig en0 | awk '/inet.[0-9]/ {printf $2}' | pbcopy -pboard general

只需将其粘贴到终端并按回车键

其次,这可能是因为您需要在您的应用程序中启用任意加载,http 调用在 iOS 9 及更高版本中默认被阻止 这里是你如何做到这一点:https://stackoverflow.com/a/40299837/2252297

希望有帮助。

【讨论】:

    猜你喜欢
    • 2012-08-31
    • 2018-09-06
    • 2015-11-26
    • 2018-02-17
    • 2017-05-03
    • 1970-01-01
    • 2011-01-20
    • 2020-12-05
    • 1970-01-01
    相关资源
    最近更新 更多