Express Framework app.post and app.get Express Framework app.post and app.get express express

Express Framework app.post and app.get


1. app.get('/', function(req, res){
This is telling express to listen for requests to / and run the function when it sees one.

The first argument is a pattern to match. Sometimes a literal URL fragment like '/' or '/privacy', you can also do substitutions as shown below. You can also match regexes if necessary as described here.

All the internal parts of Express follow the function(req, res, next) pattern. An incoming request starts at the top of the middleware chain (e.g. bodyParser) and gets passed along until something sends a response, or express gets to the end of the chain and 404's.

You usually put your app.router at the bottom of the chain. Once Express gets there it starts matching the request against all the app.get('path'..., app.post('path'... etc, in the order which they were set up.

Variable substitution:

// this would match:// /questions/18087696/express-framework-app-post-and-app-getapp.get('/questions/:id/:slug', function(req, res, next){  db.fetch(req.params.id, function(err, question){    console.log('Fetched question: '+req.params.slug');    res.locals.question = question;    res.render('question-view');  });});

next():
If you defined your handling functions as function(req, res, next){} you can call next() to yield, passing the request back into the middleware chain. You might do this for e.g. a catchall route:

app.all('*', function(req, res, next){  if(req.secure !== true) {    res.redirect('https://'+req.host+req.originalUrl);  } else {    next();  };});

Again, order matters, you'll have to put this above the other routing functions if you want it to run before those.

I haven't POSTed json before but @PeterLyon's solution looks fine to me for that.


TJ annoyingly documents this as app.VERB(path, [callback...], callback in the express docs, so search the express docs for that. I'm not going to copy/paste them here. It's his unfriendly way of saying that app.get, app.post, app.put, etc all have the same function signature, and there are one of these methods for each supported method from HTTP.

To get your posted JSON data, use the bodyParser middleware:

app.post('/yourPath', express.bodyParser(), function (req, res) {  //req.body is your array of objects now:  // [{id:134123, url:'www.qwer.com'},{id:131211,url:'www.asdf.com'}]});