Node.js

Node.js Express Back-end REST API

brightlightkim 2022. 3. 19. 14:08

Back-End

If you are using nvm

nvm use stable

Initialize a new Node project

The first step with node is to initialize a new project:

cd back-end
npm init

This will ask you a number of questions. Here is how I answered them:

package name: (node-express-vue-todo)
version: (1.0.0)
description: todo list
entry point: (script.js) server.js
test command:
git repository:
keywords:
author:
license: (ISC)

Be sure to make the entry point server.js

Now you need to install Express, which makes it easy to create a REST API, and body-parser, which makes it easy to parse incoming requests. This will automatically save these packages as dependencies in package.json:

npm install express body-parser

 

Setup

We'll start with a basic setup for a back end server. In server.js, put the following:

const express = require('express');
const bodyParser = require('body-parser');

const app = express();

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({
  extended: false
}));

// parse application/json
app.use(bodyParser.json());

app.listen(3000, () => console.log('Server listening on port 3000!'));

This is the boilerplate we'll use for a Node and Express back end. We first load the modules we need. Then we create an Express app and we configure the body parser library so that it will parse forms and JSON requests.

We start the server on port 3000.

 

REST API

Create Operation

app.post('/api/items', (req, res) => {
  id = id + 1;
  let item = {
    id: id,
    text: req.body.text,
    completed: req.body.completed
  };
  items.push(item);
  res.send(item);
});

We use post and the send send the created item with status 200.

 

Read Operation

app.get('/api/items', (req, res) => {
  res.send(items);
});

 

Updating Items

app.put('/api/items/:id', (req, res) => {
  let id = parseInt(req.params.id);
  let itemsMap = items.map(item => {
    return item.id;
  });
  let index = itemsMap.indexOf(id);
  if (index === -1) {
    res.status(404)
      .send("Sorry, that item doesn't exist");
    return;
  }
  let item = items[index];
  item.text = req.body.text;
  item.completed = req.body.completed;
  res.send(item);
});

We use put for updating items and send it with status 200 (default)

 

Delete Items

app.delete('/api/items/:id', (req, res) => {
  let id = parseInt(req.params.id);
  let removeIndex = items.map(item => {
      return item.id;
    })
    .indexOf(id);
  if (removeIndex === -1) {
    res.status(404)
      .send("Sorry, that item doesn't exist");
    return;
  }
  items.splice(removeIndex, 1);
  res.sendStatus(200);
});