Aayushi Gupta
Aayushi Gupta

Reputation: 367

NodeJS express : request.query Vs request.body

What is the difference in request.query and request.body I find them in the mapping of the Express. in GET and POST method respectively

Upvotes: 2

Views: 2347

Answers (1)

Terry Lennox
Terry Lennox

Reputation: 30685

You can set up a simple express server to show you what to expect in each of request.query and request.body:

const express = require('express');
const app = express();
const bodyParser = require('body-parser');

app.use(bodyParser.json());

app.post("/", function(req, res, next){
    console.log('Query: ', req.query);
    console.log('Body: ', req.body);
    res.status(201).json({status: 'ok'});
});

app.listen(8080);

You can then call this with curl:

curl -X POST --data "{\"state\":\"MN\", \"client_id\": 42}" -H "content-type: application/json" "http://localhost:8080?id=24&name=john+smith&age=35" -v

request.query will contain the query parameters, e.g.

Query:  { id: '24', name: 'john smith', age: '35' }

request.body will contain the body parameters, e.g.

Body:  { state: 'MN', client_id: 42 }

Upvotes: 3

Related Questions