Skip to content

Instantly share code, notes, and snippets.

@raditotev
Last active January 9, 2022 11:55
Show Gist options
  • Save raditotev/8d829464daf5dc456a297a2f81612ff3 to your computer and use it in GitHub Desktop.
Save raditotev/8d829464daf5dc456a297a2f81612ff3 to your computer and use it in GitHub Desktop.
Step by step basic set up for an express app

Building REST API with Node

  • Create project folder and run npm -y init to set up package.json

  • Optional: Set up git git init

  • Install express - npm i express

  • Create app.js in the root of the project

  • Paste following in the same file

    // app.js
    const express = require('express');
    const app = express();
    
    app.get('/', function (req, res) {
      res.send('Hello World');
    });
    
    app.listen(3000);
  • Update package.json scripts with a start

    "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1",
    
        "start": "node app.js"
      },
    
  • Test it's working - npm start and open localhost:3000 in the browser

  • Install nodemon as dev dependency, so that you don't have to restart server on every change: npm i -D nodemon

  • Update your scripts in package.json by adding a dev option:

    "scripts": {
      "test": "echo \"Error: no test specified\" && exit 1",
      "start": "node app.js"
    
      "dev": "nodemon app.js"
    }
    
  • Create the routes to your resources in a routes folder in the root of the project. For example products will be a products.js file and it can contain the following CRUD endpoints:

    // routes/products.js
    const express = require('express');
    const router = express.Router();
    
    router.get('/', (req, res, next) => {
      res.status(200).json({ message: 'Get all products' });
    });
    
    router.post('/', (req, res, next) => {
      res.status(201).json({ message: 'Create a new product' });
    });
    
    router.get('/:productId', (req, res, next) => {
      const id = req.params.productId;
      res.status(200).json({ message: `Get product with an ID ${id}` });
    });
    
    router.patch('/:productId', (req, res, next) => {
      const id = req.params.productId;
      res.status(200).json({ message: `Update product with an ID of ${id}` });
    });
    
    router.delete('/:productId', (req, res, next) => {
      const id = req.params.productId;
      res.status(200).json({ message: `Delete product with an ID of ${id}` });
    });
    
    module.exports = router;
  • Create a new folder in the root of the project named controllers and move the CRUD operations from your routes to a controller module.

    // controllers/products-controller.js
    const getProducts = (req, res, next) => {
      res.status(200).json({ message: 'Get all products' });
    }
    ...
    // create functions for the rest of the rest of teh endpoints
    
    module.exports = {
      getProducts,
      ...
    }
  • Use the methods from your controller module in your routes

    // routes/products.js
    ...
    const productsController = require('../controllers/products-controller')
    ...
    router.get('/', (req, res, next) => productsController.getProducts);
    ...
  • Use your resource routes (products in this case) in app.js:

    const express = require('express');
    const app = express();
    
    const productRoutes = require('./routes/products');
    
    app.use('/products', productRoutes);
    app.listen(3000);
    
  • Add logging - npm i morgan

    const express = require('express');
    const app = express();
    
    const morgan = require('morgan');
    
    const productRoutes = require('./routes/products');
    
    app.use(morgan('dev'));
    
    app.use('/products', productRoutes);
    
    app.listen(3000);
    
  • Add error handling - npm i http-errors

    const express = require('express');
    const app = express();
    const morgan = require('morgan');
    
    const createError = require('http-errors');
    
    const productRoutes = require('./routes/products');
    
    app.use(morgan('dev'));
    
    app.use('/products', productRoutes);
    
    // Non existing routes
    app.use((req, res, next) => {
      const error = new createError.NotFound();
      next(error);
    });
    // Error handling
    app.use((error, req, res, next) => {
      res
        .status(error.status || 500)
        .json({ message: error.message || 'Server error' });
    });
    app.listen(3000);
    
  • Add body-parser - npm i body-parser

    const express = require('express');
    const app = express();
    const morgan = require('morgan');
    const createError = require('http-errors');
    
    const bodyParser = require('body-parser');
    // Middleware
    app.use(morgan('dev'));
    
    app.use(bodyParser.urlencoded({ extended: false }));
    app.use(bodyParser.json());
  • Add allowed CORS

    // Middleware
    app.use(morgan('dev'));
    app.use(bodyParser.urlencoded({ extended: false }));
    app.use(bodyParser.json());
    
    app.use((req, res, next) => {
      res.header('Access-Control-Allow-Origin', '*');
      res.header(
        'Access-Control-Allow-Headers',
        'Origin, X-Requested-With, Content-Type, Accept, Authorization'
      );
      if (req.method === 'OPTIONS') {
        res.header(
          'Access-Control-Allow-Methods',
          'GET, POST, PUT, PATCH, DELETE'
        );
        return res.status(200).json({});
      }
      next();
    });
  • Add your resource models

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