Tuesday, 2 May 2017

Node.js parsing JSON from iOS URLSession body

Sending a JSON from an iOS device using URLSession. I'm sending:

let body = try? JSONSerialization.data(withJSONObject: order.toJSON())
// { "customer": 123 }
request.httpBody = body
request.httpMethod = "POST"
URLSession.shared.dataTask(with: request) { (data, response, error) in
    ...
}.resume()

If I print the body just after that, I do get a valid JSON:

print(String(data: request.httpBody!, encoding: .utf8)!)
// {"customer":123}

Then, in the server side nodejs I have the following code (node or javascript are not my main domain):

module.exports = function (ctx, req, res) {
    console.log(ctx.body)
    // { '{"customer": 123}': '' }
    ...

My question is, why is it adding the original JSON to a JSON key and how can avoid it?

Using JSON.parse doesn't work as it gets the hole JSON is a key of an empty value (as the example).



via aramusss

No comments:

Post a Comment