Reputation:
Hi guys I have a problem sending values with a post request to a node.js server from Swift 4 (I enter the code below), along with node.js express usage,on xcode I see the following error: Could not connect to the server. I did the tests using node.js on localhost, can anyone help me? thanks.
Swift function:
@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()
}
Server 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')
})
Upvotes: 0
Views: 1863
Reputation: 2756
First of, it depends on if you are running on a device or a simulator. If you are running on a device, you can't reach your server via localhost, because the localhost points to the device, you can only use localhost when running on a simulator; when running on a device you should specify your computer's private ip. Here is a quick shell method that will print and copy your ip:
ifconfig en0 | awk '/inet.[0-9]/ {print "\033[1m \033[31m"$2 }' && ifconfig en0 | awk '/inet.[0-9]/ {printf $2}' | pbcopy -pboard general
Just paste this in the terminal and hit enter
Second of all, this might be because you need to enable Arbitrary Loads in your app, http calls are block by default in iOS 9 and above here is how you do this: https://stackoverflow.com/a/40299837/2252297
hope that helps.
Upvotes: 3