Skip to content

Instantly share code, notes, and snippets.

@arol
Created July 14, 2017 22:30
Show Gist options
  • Save arol/de278658f681a732e7d9dbaae2afb8c8 to your computer and use it in GitHub Desktop.
Save arol/de278658f681a732e7d9dbaae2afb8c8 to your computer and use it in GitHub Desktop.
ExpressJS Guide

Express

Install

$ mkdir myapp
$ cd myapp
$ npm init #follow instructions - wizard app
$ git init
$ npm i express

Entry point

Create an index.js file, this will contain the bootstrap of your app.

const express = require('express')
const app = express()

// here will go the routing

app.listen(3000, () => {
  console.log('App started and listening on port 3000')
})

Setting up commands and running

Add start and dev commands to your package.json file so you can run your app executing npm start and npm run dev in your terminal.

// package.json

"scripts": {
  "start": "node index.js",
  "dev": "nodemon index.js"
}

Routing

Now its time to define your routes. Go to the index.js file before the listen command. It's time to define our routes:

app.get('/', (req, res, next) => {
  res.send('Hello World')
})

You can run get, post, put and delete functions for defining your methods. Also, you can pass a function reference so you write the function in another file.

const entitiesController = require('./controllers/entities.controller')

app.get('/entities', entitiesController.getEntities)
app.post('/entities', entitiesController.createEntity)
app.get('/entities/:id', entitiesController.getEntity)
// req.params.id will be available on entitiesController.getEntity call

Pay attention, this function is referenced, not executed. The router will execute it when our app receives a request.

Express routing is very powerful, you have a full guide in here

The Controller

The controller is the object or class that contains our middlewares (business logic).

const getEntities = (req, res) => {
  // You can work with your model here so you can
  // retrieve or write some data to/from the database
  res.send(/*response content*/)
}

modules.exports = {
  getEntities: getEntities,
  createEntity: createEntity
}

// OR using ES6 construction
// modules.exports = {
//   getEntities,
//   createEntity
// }

The model

In here we're going full opinionated, we're deciding to work with MongoDB and mongoose (totally outside the express domain).

npm i mongoose

Create a db.js file in the root folder and connect to the db in it. You only have to import it from the index.js (require('db'))

// db.js

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/myDB');

var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
  // we're connected!
});

Then you can create your model file in models/entity.js and create the schema in it.

// models/entity.js
var entitySchema = mongoose.Schema({
    name: String
});

var Entity = mongoose.model('Kitten', kittySchema);

module.exports = Entity;

Finally, require it in your controller and start working with the db data!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment