Since I’m playing with Express at the moment I’ve updated my collection of snippets to include a few things I seem to be doing regularly:

Express setup

I use the shortcut “myExpressSetup” to kick off all my new Express projects. It has basically all the parts I need to get the project underway, and means I dont have to remeber each bit. This is more or less the Express equivalent of the HTML boilerplate I’ve mentioned in the past.

  'Express Setup':
    'prefix': 'myExpressSetup'
    'body': """
    "use strict"

    var express = require( "express" );
    var app = express();
    var bodyParser = require( "body-parser" );

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

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

    app.get( "/", function( request, response ) {
      response.render( "home" );
    } )

    $1

    app.get( "*", function( request, response ) {
      response.send( "404 page not found );
    } )

    // Tells express to listen for requests (Start server)

    app.listen( 3000, function() {
      console.log( "The server started on http://localhost:3000/" );
    } );
    """

Get route

Shocking no one, if there’s one thing I seem to be doing a lot it’s displaying content on an HTML page. Using the shortcut “myGetRoute” this one basically says if the URL fits this pattern take it and display it using the “project” template.

'Express Get':
    'prefix': 'myGetRoute'
    'body': """
    app.get( "/project/:thing", function( request, response ) {
      let thing = request.params.thing
      response.render( "project", {
        thingVar: thing
      } );
    } );
    """

So, for example, I could have a URL like geekpulp.co.nz/project/banana and have it populate the project templates H1 with “banana”. If the URL was then geekpulp.co.nz/project/apple it would populate the project template H1 with Apple. Obviously later in the course, I’ll start populating things from a database and this will all make a lot more sense.

Post route

This one’s all about collecting data from a form and adding it back to the page. Again this sort of thing will make a lot more sense when I’m actually posting the data to a database. At the moment if you refresh the page everything will just return to defaut values because nothing is being saved to the backend.

'Express Push':
    'prefix': 'myPushRoute'
    'body': """
    app.post( "/addteam", function( request, response ) {
      let newTeam = request.body.newTeam;
      teams.push( newTeam );
      response.redirect( "/teams" );
    } );
    """

These new snippets are certain to change in the next week or so as I expand to doing things that are actually useful. At this stage, a lot of this stuff is just code that facilities learning. Having said that, I find making snippets for repetitive tasks a good habit to form. Ultimately the whole point is being as efficient as possible.


Posted

in

, , ,

by