3. Crazy geek


The original:
https://medium.freecodecamp.o…


This article first send WeChat messages public number: front-end pioneer welcome attention, every day to you push fresh front-end technology articles


Node.js can be prohibitive to beginners, and its flexible structure and lack of strict specifications make it seem complex.

This tutorial is a quick guide to Node.js, the Express framework, and MongoDB, focusing on basic REST routing and basic database interaction. You’ll build a simple API framework template that can then be used for any application.

This tutorial applies: You should have a basic understanding of REST APIs and CRUD operations, as well as a basic knowledge of JavaScript. I used ES6 (mainly arrow functions), but it wasn’t too complicated.

In this tutorial, we will create a skeleton for the back end of a web note-taking application – similar to Google Keep – that can perform all four CRUD operations: create, read, update, and delete.

configuration

If you don’t have Node installed, see here.

Create a new directory, run NPM init, then follow the tips and name your app notable (or whatever else you might like).

npm init

Once that’s done, you’ll have a package.json file in your directory. You are ready to install the dependencies needed for your project.

We’ll use Express as our framework, MongoDB as our database, and a package called Body-Parser to help process JSON requests.

NPM install --save express [email protected] body parser

I also strongly recommend installing Nodemon as a dev dependency. This is a very simple package that automatically restarts the server when a file is changed.

If you run:

npm install --save-dev nodemon

Then add the following script to package.json:

// package.json
  "scripts": {
    "dev": "nodemon server.js"
  },

The complete package.json should look like this:

/ / package. Json {" name ":" for ", "version" : "1.0.0", "description" : ""," main ":" server. Js ", "scripts" : {" dev ": "Nodemon server. Js"}, "author" : ""," license ":" ISC ", "dependencies" : {" body - the parser ":" ^ 1.15.2 ", "express" : "^ 4.14.0", "directing" : "^ 2.2.16"}, "devDependencies" : {" nodemon ":" ^ 1.11.0 "}}

Now you can create the Server.js file and build the API.

Our server

First, import all the dependencies in Server.js.

// server.js
const express        = require('express');
const MongoClient    = require('mongodb').MongoClient;
const bodyParser     = require('body-parser');
const app            = express();

We will use MongoClient to interact with the database. The application is also initialized as an instance of the Express framework.

The last thing is to tell your program to start listening for requests.

You can specify a port and start listening like this:

// server.js
const port = 8000;
app.listen(port, () => {
  console.log('We are live on ' + port);
});

Now, if you’re running NPM run dev (or Node Server.js, if you don’t have Nodemon installed), you should see the “We are living on port 8000” prompt in your terminal.

Your server has started. But it can’t do anything yet.

Now let’s solve this problem.

CRUD routing

For this example, you’ll build four routes; Create notes, read notes, update notes, and delete notes.

This will give you an idea of how to use Node to build almost all basic routes.

However, to test your API, you also need to make requests that mimic the client. To do this, we’ll use a nice application called PostMan. It allows you to make simple HTTP requests with custom headers and parameters.

With PostMan installed, let’s set up the route.

The project structure

Most Node.js tutorials (and many real-world examples) put all routes in one large Routes.js file. It makes me a little uncomfortable. By contrast, splitting files into separate folders can improve readability and make large applications easier to manage.

We’re not making big apps, but we can still do this. Create the following directory: An app folder with a routes folder and routes with index.js and Note_routes.js files.

mkdir app
cd app
mkdir routes
cd routes
touch index.js
touch note_routes.js

These directories may seem excessive for your simple little program, but it always makes sense to get it right from the start.

Your first route

Let’s start with C in CRUD. How would you create a note?

Well, before you start, you have to lay the groundwork. In Express, the route is contained in a function that takes the Express instance and the database as parameters.

Like this:

// routes/note_routes.js
module.exports = function(app, db) {
};

Then, you can export this function via index.js:

// routes/index.js
const noteRoutes = require('./note_routes');
module.exports = function(app, db) {
  noteRoutes(app, db);
  // Other route groups could go here, in the future
};

Then import it for use in Server.js:

// server.js
const express        = require('express');
const MongoClient    = require('mongodb').MongoClient;
const bodyParser     = require('body-parser');
const app            = express();
const port = 8000;
require('./app/routes')(app, {});
app.listen(port, () => {
  console.log('We are live on ' + port);
});

Note that since you haven’t set up the database yet, you only need to pass in an empty object.

Okay, now you can make your own CREATE route.

The syntax is simple:

// note_routes.js
module.exports = function(app, db) {
  app.post('/notes', (req, res) => {
    // You'll create your note here.
    res.send('Hello')
  });
};

When the application receives a POST request to the ‘/ Notes’ path, it executes the code inside the callback — the request object (which contains the request’s parameters or JSON) and the response object.

You can test this by sending a POST request to localhost:8000/notes using PostMan.

You should get a reply: ‘Hello’.

That’s great! You’ve created your first true route.

The next step is to add some parameters to your request and process them in the API before adding them to your database.

Request parameters

In PostMan, after selecting the x-www-form-urlencoded radio button, go to the Body TAB and add some key-value pairs.

This will add the encoded form data to your request, which you can process using the API.

You can try more Settings.

Now in your Note_Routes.js, let’s output the body content.

// note_routes.js
module.exports = function(app, db) {
  app.post('/notes', (req, res) => {
    console.log(req.body)
    res.send('Hello')
  });
};

Send the request to PostMan and you will see… Undefined.

Unfortunately, Express can’t handle URL-encoded forms on its own. Although you do have the body-parser package installed……

// server.
const express        = require('express');
const MongoClient    = require('mongodb').MongoClient;
const bodyParser     = require('body-parser');
const app            = express();
const port = 8000;
app.use(bodyParser.urlencoded({ extended: true }));
require('./app/routes')(app, {});
app.listen(port, () => {
  console.log('We are live on ' + port);
});

Now you should see the body as an object in the terminal. Now you should think of the Body as an object in the terminal.

{ title: 'My Note Title', body: 'What a great note.' }

The last step of the first route: Set up the database, and then add the data.

The easiest way to set up the Mongo database is through MLab: it’s minimal, it’s free and it’s very fast to set up.

After creating the account and deploying MongoDB, add the user’s username and password to the database:

Then copy the second URL here:

In the directory configuration of the project root, create a db.js file.

mkdir config 
cd config
touch db.js

Inside, add the previous URL:

module.exports = {
  url : YOUR URL HERE
};

Don’t forget to add your username and password (from the database user, not your MLab account) to the URL. (If you are submitting this project to GitHub, be sure to include the.gitignore file like this, and don’t share your password with anyone.)

Now that you can connect to the database with MongoClient in your Server.js, use it to wrap your application Settings:

// server.js
const express        = require('express');
const MongoClient    = require('mongodb').MongoClient;
const bodyParser     = require('body-parser');
const db             = require('./config/db');
const app            = express();
const port = 8000;
app.use(bodyParser.urlencoded({ extended: true }));
MongoClient.connect(db.url, (err, database) => {
  if (err) return console.log(err)
  require('./app/routes')(app, database);
  app.listen(port, () => {
    console.log('We are live on ' + port);
  });               
})

If you are using the latest version of MongoDB (3.0+), please change it to:

// server.js const express = require('express'); const MongoClient = require('mongodb').MongoClient; const bodyParser = require('body-parser'); const db = require('./config/db'); const app = express(); const port = 8000; app.use(bodyParser.urlencoded({ extended: true })); MongoClient.connect(db.url, (err, database) => { if (err) return console.log(err) // Make sure you add the database name and not the collection name const  database = database.db("note-api") require('./app/routes')(app, database); app.listen(port, () => { console.log('We are live on ' + port); }); })

This is the last setup for your infrastructure!

Add to your database

MongoDB stores data in Collections. In your project, you want to store your notes in a collection called Notes.

Since the database is passed in as a db parameter in the path, it can be accessed like this:

db.collection('notes')

Creating a note is as simple as calling INSERT on a collection:

const note = { text: req.body.body, title: req.body.title}
  db.collection('notes').insert(note, (err, results) => {
}

After the insert completes (or fails for some reason), either an error is returned or the newly created note object is reversed. Here’s the complete Note_Routes.js code:

// note_routes.js module.exports = function(app, db) { const collection = app.post('/notes', (req, res) => { const note = { text: req.body.body, title: req.body.title }; db.collection('notes').insert(note, (err, result) => { if (err) { res.send({ 'error': 'An error has occurred' }); } else { res.send(result.ops[0]); }}); }); };

Give it a try! Send x-www-form-urlencoded POST requests using PostMan, and set the title and Body under the Body TAB.

The response should look like this:

If you log into MLab, you should also be able to see the notes created in the database.

READ the routing

Now you can pick up the pace a little bit.

Suppose you want to get the newly created note by navigating to localhost:8000/notes/{id}. This is the link should be localhost: 8000 / notes / 585182 bd42ac5b07a9755ea3. (If you don’t get the ID of the note in it, you can check MLab or create a new note).

Here’s what’s in Note_Routes.js:

// note_routes.js module.exports = function(app, db) { app.get('/notes/:id', (req, res) => { }); app.post('/notes', (req, res) => { const note = { text: req.body.body, title: req.body.title }; db.collection('notes').insert(note, (err, result) => { if (err) { res.send({ 'error': 'An error has occurred' }); } else { res.send(result.ops[0]); }}); }); };

As before, you will call a method in a database collection. Here, it is aptly named findOne.

// note_routes.js module.exports = function(app, db) { app.get('/notes/:id', (req, res) => { const details = { '_id': <ID GOES HERE> }; db.collection('notes').findOne(details, (err, item) => { if (err) { res.send({'error':'An error has occurred'}); } else { res.send(item); }}); }); app.post('/notes', (req, res) => { const note = { text: req.body.body, title: req.body.title }; db.collection('notes').insert(note, (err, result) => { if (err) { res.send({ 'error': 'An error has occurred' }); } else { res.send(result.ops[0]); }}); }); };

You can get the ID from the URL parameter by req.params.id. However, if you try to insert the string into the

position above, it will not work properly.

MongoDB not only requires that IDs be strings, but also that IDs be objects, which are called ObjectID.

Don’t worry, it’s easy to fix. Here’s the complete code:

// note_routes.js var ObjectID = require('mongodb').ObjectID; module.exports = function(app, db) { app.get('/notes/:id', (req, res) => { const id = req.params.id; const details = { '_id': new ObjectID(id) }; db.collection('notes').findOne(details, (err, item) => { if (err) { res.send({'error':'An error has occurred'}); } else { res.send(item); }}); }); app.post('/notes', (req, res) => { const note = { text: req.body.body, title: req.body.title }; db.collection('notes').insert(note, (err, result) => { if (err) { res.send({ 'error': 'An error has occurred' }); } else { res.send(result.ops[0]); }}); }); };

Try using a note ID that looks like this:

DELETE the routing

In fact, deleting an object is almost the same as finding one. You simply replace findOne with the remove function. Here’s the complete code:

// note_routes.js
// ...
  app.delete('/notes/:id', (req, res) => {
    const id = req.params.id;
    const details = { '_id': new ObjectID(id) };
    db.collection('notes').remove(details, (err, item) => {
      if (err) {
        res.send({'error':'An error has occurred'});
      } else {
        res.send('Note ' + id + ' deleted!');
      } 
    });
  });
// ...

UPDATE the routing

The last one! The PUT method is basically a hybrid of READ and CREATE. You find the object, and you update it. If you just deleted the only note in the database, create another one!

Code:

// note_routes.js // ... app.put('/notes/:id', (req, res) => { const id = req.params.id; const details = { '_id': new ObjectID(id) }; const note = { text: req.body.body, title: req.body.title }; db.collection('notes').update(details, note, (err, result) => { if (err) { res.send({'error':'An error has occurred'}); } else { res.send(note); }}); }); / /...

Now you can update any notes as follows:

Note that the code isn’t perfect — for example, if you don’t provide a body or a title, the PUT request will invalidate those fields on the notes in the database.

API to complete

It’s that simple! You’ve completed the Node API for CRUD operations.

The goal of this tutorial is to familiarize you with Express, Node, and MongoDB — you can use simple programs as springboards to more complex projects.

In the future I will write a series of tutorials to create simpler APIs in different languages and frameworks. If you are interested, please click here!


This article first send WeChat messages public number: front-end pioneer

Welcome to scan the two-dimensional code to pay attention to the public number, every day to push you fresh front-end technology articles


Read on for the other great articles in this column:

  • 12 Amazing CSS Experiment Projects
  • 50 React Interview Questions You Must Know
  • What are the front-end interview questions at the world’s top companies
  • 11 of the best JavaScript dynamic effects libraries
  • CSS Flexbox Visualization Manual
  • React from a designer’s point of view
  • The holidays are boring? Write a little brain game in JavaScript!
  • How does CSS sticky positioning work
  • A step-by-step guide to implementing animations using HTML5 SVG
  • Programmer 30 years old before the monthly salary is less than 30K, which way to go
  • 14 of the best JavaScript data visualization libraries
  • 8 top VS Code extensions for the front end
  • A complete guide to Node.js multithreading
  • Convert HTML to PDF 4 solutions and implementation

  • More articles…