0

I've setup the api post request which is working fine with postman, however in my swift code it doesn't send the params with the request.

let parameters = ["spotId" : spotId,
                      "voteruptime" : currentDate,
                      "voterupid" : userId] as [String : Any]

    guard let url = URL(string: "http://example.com:3000/upvote") else { return }
    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.addValue("Application/json", forHTTPHeaderField: "Content-Type")
    guard let httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: []) else { return }
    request.httpBody = httpBody
    print(request.httpBody)

    let session = URLSession.shared
    session.dataTask(with: request) { (data, response, error) in
        if let response = response {
            print(response)
        }

        if let data = data {
            do {
                let json = try JSONSerialization.jsonObject(with: data, options: [])
                print(json)
            } catch {
                print(error)
            }
        }

        }.resume()

I got a response

<NSHTTPURLResponse: 0x618000a26560> { URL: http://example.com:3000/upvote } { status code: 200, headers {
Connection = "keep-alive";
"Content-Length" = 28;
"Content-Type" = "application/json; charset=utf-8";
Date = "Sat, 21 Oct 2017 03:11:46 GMT";
Etag = "W/\"1c-BWaocQVSSeKjLiaYjOC8+MGSQnc\"";
"X-Powered-By" = Express;} }

{
    n = 0;
    nModified = 0;
    ok = 1;
}

The server code Node JS is:

app.post('/upvote', function(req, res){

    Spots.update({_id: req.query.spotId},{$push:{'upvotes':{'voterupid':req.query.voterupid,'voteruptime':req.query.voteruptime}}},function( err, Spots){
    console.log(req.url)


if(err){
                throw err;
                }
    res.json(Spots);
});

});

I tried also alamofire, and it's the same issue, no params sent to the server.

Thamer
  • 13
  • 4

1 Answers1

0

I believe the issue is that req.query accesses data passed on the query string, whereas you are POSTing the data in the body of the request.

To access the body, you need to use body-parser as described in multiple answers here: How to access the request body when POSTing using Node.js and Express?

Mike Taverne
  • 8,358
  • 2
  • 35
  • 50