大家好我在发送带有post请求的值到Swift 4的node.js服务器(我输入下面的代码),以及node.js表达用法时遇到问题,在xcode上我看到以下错误:无法连接到服务器。我在localhost上使用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')
})
答案 0 :(得分:3)
首先,它取决于您是在设备还是模拟器上运行。 如果您在设备上运行,则无法通过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
只需将其粘贴到终端并按Enter键
即可其次,这可能是因为您需要在应用中启用任意负载,默认情况下,http调用在iOS 9及更高版本中是阻止的 以下是您执行此操作的方式:https://stackoverflow.com/a/40299837/2252297
希望有所帮助。