Querystring and Post Parameters

  • Express can pass the query string(get method only) and attach it to req.query object

What query string look like

Query String -- get Query String -- json

  • Be aware of the Content-Type

What about post a form or JSON object?

  • You need a parser to parse the body
  • We can use body parser (it can parse the body of the request)
  • Body parser middleware also has a json parser function

The Code

var express = require('express');
//require the body parser
var bodyParser = require('body-parser');
var app = express();

var port = process.env.PORT || 3000;

//init the body parse, just copy the code from documenetation, don't understand yet
var urlencodedParser = bodyParser.urlencoded({ extended: false });
//this middleware also has json parser
var jsonParser = bodyParser.json();

app.use('/assets', express.static(__dirname + '/public'));

app.set('view engine', 'ejs');

app.use('/', function (req, res, next) {
    console.log('Request Url:' + req.url);
    next();
});

app.get('/', function(req, res) {
    res.render('index');
});

app.get('/person/:id', function(req, res) {
    //Qstr is the value from localhost:3000/person?qstr=123
    res.render('person', { ID: req.params.id, Qstr: req.query.qstr });
});

//when a request post to /person, run the parser and than run our function
app.post('/person', urlencodedParser, function(req, res) {
    res.send('Thank you!');
    //reql.body is added by the body parser function
    console.log(req.body.firstname);
    console.log(req.body.lastname);
});

app.post('/personjson', jsonParser, function(req, res) {
    //we are sending response directly, we don't use a view or template engine whatsoever
    res.send('Thank you for the JSON data!');
    console.log(req.body.firstname);
    console.log(req.body.lastname);
});

app.get('/api', function(req, res) {
    res.json({ firstname: 'John', lastname: 'Doe' });
});

app.listen(port);

results matching ""

    No results matching ""