Developing a Backend API with Node.js and Express

0

Category :

In the following sections, you will build a simple Q&A (Question & Answer) app that will allow users to interact with each other asking and answering questions. To make the whole process more realistic, you will use Node.js and Express to create a rough backend API.

Developing a Backend API with Node.js and Express

build a backend API to support your Q&A app. In this section, you will use Express alongside with Node.js to create this API. With this library, as you will see here, you can quickly build apps to run on servers
# use NPM to start the project
npm init -y

this will create a file called package.json inside your directory. This file will hold the details (like the dependencies) of your backend API.

npm i body-parser cors express helmet morgan
This command will install five dependencies in your project:
  1. body-parser:
    This is a library that you will use to convert the body of incoming requests into JSON objects.
  2. cors:
    This is a library that you will use to configure Express to add headers stating that your API accepts requests coming from other origins. This is also known as Cross-Origin Resource Sharing (CORS).
  3. express:
    This is Express itself.
  4. helmet:
    This is a library that helps to secure Express apps with various HTTP headers.
  5. morgan:
    This is a library that adds some logging capabilities to your Express app.

Also, you will see a new file called package-lock.json. NPM uses this file to make sure that anyone else using your project (or even yourself in other environments) will always get versions compatible with those that you are installing now.

Then, the last thing you will need to do is to develop the backend source code. So, create a directory called src inside your qa-api directory and create a file called index.js

//import dependencies
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const helmet = require('helmet');
const morgan = require('morgan');

// define the Express app
const app = express();

// the database
const questions = [];

// enhance your app security with Helmet
app.use(helmet());

// use bodyParser to parse application/json content-type
app.use(bodyParser.json());

// enable all CORS requests
app.use(cors());

// log HTTP requests
app.use(morgan('combined'));

// retrieve all questions
app.get('/', (req, res) => {
  const qs = questions.map(q => ({
    id: q.id,
    title: q.title,
    description: q.description,
    answers: q.answers.length,
  }));
  res.send(qs);
});

// get a specific question
app.get('/:id', (req, res) => {
  const question = questions.filter(q => (q.id === parseInt(req.params.id)));
  if (question.length > 1) return res.status(500).send();
  if (question.length === 0) return res.status(404).send();
  res.send(question[0]);
});

// insert a new question
app.post('/', (req, res) => {
  const {title, description} = req.body;
  const newQuestion = {
    id: questions.length + 1,
    title,
    description,
    answers: [],
  };
  questions.push(newQuestion);
  res.status(200).send();
});

// insert a new answer to a question
app.post('/answer/:id', (req, res) => {
  const {answer} = req.body;

  const question = questions.filter(q => (q.id === parseInt(req.params.id)));
  if (question.length > 1) return res.status(500).send();
  if (question.length === 0) return res.status(404).send();

  question[0].answers.push({
    answer,
  });

  res.status(200).send();
});

// start the server
app.listen(8081, () => {
  console.log('listening on port 8081');
});
With this file in place, you are good to go. To run your app, just issue the following command:
# from the qa-app directory
node src

Test if everything is really working, open a new terminal and issue the following commands:

# issue an HTTP GET request
curl localhost:8081

# issue a POST request
curl -X POST -H 'Content-Type: application/json' -d '{
  "title": "How do I make a sandwich?",
  "description": "I am trying very hard, but I do not know how to make a delicious sandwich. Can someone help me?"
}' localhost:8081

curl -X POST -H 'Content-Type: application/json' -d '{
  "title": "What is React?",
  "description": "I have been hearing a lot about React. What is it?"
}' localhost:8081

# re-issue the GET request
curl localhost:8081
With your backend API up and running, you are finally ready to start developing your React application.

my thanks to this great blog post:
https://auth0.com/blog/react-tutorial-building-and-securing-your-first-app/

0 comments:

Post a Comment