【发布时间】: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