Express Framework app.post and app.get

jensiepoo picture jensiepoo · Aug 6, 2013 · Viewed 24.8k times · Source

I am fairly new to the express framework. I couldn't find the documentation for application.post() method in the express API reference. Can someone provide a few examples of all the possible parameters I can put in the function? I've read a couple sites with the following example, what does the first parameter mean?

  1. I know the second parameter is the callback function, but what exactly do we put in the first parameter?

    app.post('/', function(req, res){
    
  2. Also, let's say we want the users to post(send data to our server) ID numbers with a certain format([{id:134123, url:www.qwer.com},{id:131211,url:www.asdf.com}]). We then want to extract the ID's and retrieves the data with those ID's from somewhere in our server. How would we write the app.post method that allows us to manipulate the input of an array of objects, so that we only use those object's ID(key) to retrieve the necessary info regardless of other keys in the objects. Given the description of the task, do we have to use app.get() method? If so, how would we write the app.get() function?

Thanks a lot for your inputs.

Answer

Plato picture Plato · Aug 6, 2013

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-get

app.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.