[英]Send post request from Swift 4 to Node.js
嗨,大家好,我在Swift 4向我的node.js服務器發送帶有請求請求的值時遇到問題(我在下面輸入代碼),以及在xcode上的node.js表達用法,我看到以下錯誤:無法連接到服務器。 我在本地主機上使用node.js進行了測試,有人可以幫助我嗎? 謝謝。
迅捷功能:
@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')
})
首先,這取決於您是在設備還是模擬器上運行。 如果您正在設備上運行,則無法通過localhost訪問服務器,因為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
其次,這可能是因為您需要在應用中啟用任意加載,默認情況下,iOS 9和更高版本中阻止了HTTP調用,這是您的操作方式: https : //stackoverflow.com/a/40299837/2252297
希望能有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.