Peter Pik Peter Pik - 1 month ago 15
Node.js Question

connection between nodejs api and swift app

i'm trying to create an api, which my ios app is connected to. However i keep getting prompt that

error: not found
when i run post request on and set the parameters to
id, name, birth and country
. however if i just run
url/users/14253/test/10-20-1992/denmark
in postman it works fine, so i'm a bit confused what i do wrong?

api route

router.post('/:id/:name/:birth/:country', function(req, res, next) {

var params = req.params;

var accessHeader = req.headers;


var user = new User({
_id: params.id,
name: params.name,
birthday: new Date(params.birth),
country: params.country
});

user.save(function(err) {
if (err) {
res.send(err);
} else {
res.json({ message: 'User created!' });
}
});


});


swift alamofire request

func passUserData(id: String, name: String, birth: String, country: String, token: AccessToken) {

let headers = [
"Content-Type": "application/x-www-form-urlencoded"
]

Alamofire.request("http://url/users", method: .post, parameters: ["id" : id, "name" : name, "birth" : birth, "country" : country], encoding: JSONEncoding.default, headers: headers).responseString { closureResponse in
if String(describing: closureResponse.result) == "SUCCESS"
{
print(closureResponse)
} else {
print(closureResponse)

}}
}

Answer

Either you pass the parameters in the url :

 Alamofire.request("http://172.20.10.2:3000/users/" + id + "/" + name + "/" + birth + "/" + country, ...);

Either you pass the parameters in the body :

router.post('/users', function(req, res, next) {

  var body = req.body;

  var accessHeader = req.headers;


  var user = new User({
    _id: body.id,
    name: body.name,
    birthday: new Date(body.birth),
    country: body.country
  });

  user.save(function(err) {
    if (err) {
      res.send(err);
    } else {
      res.json({ message: 'User created!' });
    }
  });


});