Express body parser entire request body is key with no value

3162 views ios
5

I want to get values the body in a post using express node.js and an iOS client. Here is my server code:

app.post('/user', function (req, res) {
  console.log(req.body)
  console.log(req.body.firstName)
  var user = models.User.create({
      firstName: req.body.firstName,
      lastName: req.body.lastName,
     id: uuidV1(),
  });
  res.send(user.toJSON())
})

On the client here is what I'm doing with the json body:

let json = ["firstName": "First Dude",
                "lastName": "Last dude"]
    let body = try! JSONSerialization.data(withJSONObject: json, options: [])

When I hit the endpoint I get:

{ '{"lastName":"Last dude","firstName":"First Dude"}': '' }
undefined

Which looks like the key is the entire son body and the value is empty.

req.body.firstName is also undefined.

How can I get a value from a key using body parser?

answered question

1 Answer

11

I dont know what exacly

models.User

is ?

But In this part :

app.post('/user', function (req, res) {
  console.log(req.body)
  console.log(req.body.firstName)
  var user = models.User.create({
      firstName: req.body.firstName,
      lastName: req.body.lastName,
     id: uuidV1(),
  });
  res.send(user.toJSON())
})

You should write

res.json(user.toJSON())

instead of

res.send(user.toJSON())

posted this

Have an answer?

JD

Please login first before posting an answer.