0

I would like to know how to extract the post data from req.body.

My post data is

{
 name:'asdf',
 completed: false,
 note: 'asdf'
}

When I am trying to console it using JSON.stringify , I am getting req.body as

{"{\n name:'asdf',completed:false,note:'asdf'}":""}

I noticed that new line and colon are getting added to the req.body object. So when I am trying to filter req.body.name its returning me undefined.

I have used app.use(bodyParser.json());but still I am not getting the actual result

Hence I would like to know the following: 1. How to filter the post object? 2. Why new lines and colon are getting added to req.body object?

Gopinath Shiva
  • 3,822
  • 5
  • 25
  • 48
  • Are you setting the header data-type of the POST to JSON? – royhowie Feb 26 '15 at 04:23
  • I am using advance rest client for sending the request, I have set Content-Type = application/json and I am passing data as {'name':'asdf', 'completed':false, 'note':'asdf'} – Gopinath Shiva Feb 26 '15 at 04:30
  • previously by mistake , I set content-type as application/x-www-form-url encoded. Now when I set it to application/json , I am getting response as bad request. What am I missing? – Gopinath Shiva Feb 26 '15 at 04:31
  • can you stringify the data before you post it? – royhowie Feb 26 '15 at 04:32
  • I tried it by stringifying as "{'name':'asdf', 'completed':false, 'note':'asdf'}" , but still I am getting as bad request – Gopinath Shiva Feb 26 '15 at 04:36
  • please show me your code.. –  Feb 26 '15 at 04:41
  • @gopinathshiva set the content type back to x-www-form-url encoded, then send the data stringified. On the server, parse it. – royhowie Feb 26 '15 at 04:43
  • I dont feel passing data as stringified would be a correct solution. Anyway I found answer myself. Appreciate your help dude. Happy coding :) – Gopinath Shiva Feb 26 '15 at 04:56

2 Answers2

0

I found solution myself by following req.body empty on posts

As I am testing in rest-client, The mistakes I did are,

  1. I initially made content-type:www-form-urlencoded. Then later I made it as application/json
  2. I didnt use quotes for key in key-value pair. so you need to pass data in raw section as

    {"name":"asdf", "completed":false, "note":"asdf"}

Note: Though www-form-urlencoded also work, when you are passing data in form section as

name      asdf
completed false
note      asdf
Community
  • 1
  • 1
Gopinath Shiva
  • 3,822
  • 5
  • 25
  • 48
0

All the parsers accept a type option which allows you to change the Content-Type that the middleware will parse.

// parse various different custom JSON types as JSON 
app.use(bodyParser.json({ type: 'application/*+json' }))

// parse some custom thing into a Buffer 
app.use(bodyParser.raw({ type: 'application/vnd.custom-type' }))

// parse an HTML body into a string 
app.use(bodyParser.text({ type: 'text/html' }))