MatterGoal
MatterGoal

Reputation: 16430

NodeJs, Express, BodyParse and JSON

I'm trying to implement a simple server using Express 4.0 and parsing messages with BodyParser. To test my server I use Postman.

Using x-www-form-urlencoded as message mode it works with no problem but changing messages with JSON I can't parte data using BodyParse.

Here is my code:

app.use(bodyParser.json());

app.use(bodyParser.urlencoded({
  extended: true
}));

var router = express.Router()

router.get('/', function (req, res){

    res.json({message: "nd..."})
})

var sendRoute = router.route('/msg')
sendRoute.post(function(req, res){ 

    // HERE IS THE PROBLEM******************************
// It works with urlencoded request but not with JSON 
    var dataparam1 =    req.body.param1
    var dataparam2 =    req.body.param2
    ****************************************************
    .
    .
    .
})

and let's say this is the JSON data I get form the request:

[{"param1":"This is the param1", 
  "param2":"This is the param2"
}]

What's wrong with my code? how can I get params sent with JSON format?

Upvotes: 1

Views: 803

Answers (1)

RickN
RickN

Reputation: 13500

If your request body is sent as a JSON string, then you must tell your app that via a content-type header.

  1. In Postman, click the Headers button, next to the drop-down to select the method and the URL params button. (Top right)
  2. A table will expand, fill in Content-Type in the left field and application/json in the right field.
  3. Submit the request.

bodyParser can handle multiple types of data, but it must know what format you're submitting. It will not attempt to guess the data type.

The drop-down menu (according to your comment, it's set to 'JSON' at the moment) just above the textarea where you fill in the request body only toggles syntax highlighting, it does not set the Content-Type header for you.

Upvotes: 4

Related Questions