Skip to content

Setup Node-API

1. Preparation

  1. Model your data in json
    {
    name: Simba, 
    age: 2
    }
  2. Setup routing blueprint with http verbs: GET, POST, PUT, DELETE (REST) and CRUD (create, read , update, delete) in json or YAML
    {
    "GET /users" : {
    desc: "Gets all the users",
    response: "200 application/json",
    "data": [{},{}]
    },
    "GET /users/:id" : {
    desc: "Gets a user with an id",
    response: "200 application/json",
    "data": {}
    },
    "POST /users" : {
    desc: "Creates and returns a user with the posted update object",
    response: "201 application/json",
    "data": {}
    },
    "PUT /users/:id" : {
    desc: "Update a user with the posted update object",
    response: "200 application/json",
    "data": {}
    },
    "DELETE /users/:id" : {
    desc: "Deletes and returns a user",
    response: "200 application/json",
    "data": {}
    }
    }
    

2. Create project code

  1. Create a folder in terminal and navigate to it
  2. Create a package.json file
     yarn init

    You need to fill in the name, git repository url, …
    Choose only lowercase letters for the name (convention)

  3. Install dependencies : use a http-based framework instead of the build-in http module in node: Express (de facto framework, easy to use, many plugins, DB agnostic) . The rest of the frameworks are mostly based on Express: Koa, Hapi…
     yarn add express
  4. Create a ./src/index.js file and run it in terminal with node index.js to test the port
     const express = require('express')
    const app = express()
    
    const PORT = 3000;
    
    app.get('/', (req, res) => res.send('Hello World!'))
    app.listen(PORT, () => console.log(`API on port ${PORT}!`))
    
  5. Add a .gitignore-file and add /node_modules

    Install git (Setup git

  6. Install webpack dev-dependencies to run the backend server with webpack and run it in terminal with yarn start
     yarn add --dev webpack webpack-cli start-server-webpack-plugin

    Add a webpack.config.js file on the root to run the server automatically after the webpack build has completed

     
    const webpack = require('webpack')
    const StartServerPlugin = require('start-server-webpack-plugin')
    
    module.exports = {
      target: 'node',
      plugins: [
          new StartServerPlugin('main.js'),
          new webpack.HotModuleReplacementPlugin()
      ],
    };
  7. Add hot reloading by adapting the webpack.config.js file with an extra plugin, watch to true, and the entry files (Nodemon restarts the server on changes and as a result the state’ is erased. Hot reloading only updates the changes and keeps the state. )
     
      entry: ['webpack/hot/poll?1000', './src/index'],
      watch: true,
    plugins: [
          new webpack.HotModuleReplacementPlugin()
      ]
    

    Adapt the index.js file

    ./src/index.js
    import app from './server' import http from 'http' // only wrap the express app in the http build-in module from node if you need hot-reloading or web sockets const server = http.createServer(app); let currentApp = app; // define the port where the API lives server.listen(3000, () => { console.log('API on port 3000') }) // module is a build-in global in node // enable hot reloading if(module.hot) { module.hot.accept(['./server'], () => { server.removeListener('request', currentApp) server.on('request', app) currentApp = app }) }

    Adapt the server.js file and run from terminal with npm run start

    ./src/server.js
    import express from 'express'; // create an express based app const app = express(); app.get('/', (req, res) => { res.header("Access-Control-Allow-Origin", "http://localhost:3000"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); res.send([{id: 1, name: 'Catherine'}, {id: 2, name: 'Joris'}]); }); // you could use a fall back route to show fe an error message howevver a standard 404 error is better app.all('*', (req, res) => { res.json({catchAllOtherRoutes: true}); }); export default app;

    Adapt the package.js file and run from terminal with npm run start

    ./package.json
    "scripts": { "start": "webpack --colors --progress" },
Published inNode

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *