Home > Web Front-end > JS Tutorial > How to quickly build an API server with Node.js?

How to quickly build an API server with Node.js?

青灯夜游
Release: 2020-09-01 10:00:29
forward
2005 people have browsed it

How to quickly build an API server with Node.js?

Node.js can be intimidating to beginners, with its flexible structure and lack of strict specifications making it seem complex. [Video tutorial recommendation: node js tutorial]

This tutorial is a quick guide to Node.js, 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 in any application.

This tutorial is for : You should have a basic understanding of REST API and CRUD operations, as well as basic JavaScript knowledge. I'm using ES6 (mostly arrow functions), but it's not very complicated.

In this tutorial, we will create the backend skeleton of a web note-taking application - similar to Google Keep, capable of performing all four CRUD operations: create, read, Updates and deletions.

Configuration

If you do not have Node installed, See here.

Create a new directory, run npm init, then follow the prompts and name your application "notable" (or something else you might prefer).

npm init
Copy after login

Once completed, there will be a package.json file in your directory. You can start installing the dependencies required for your project.

We will use Express as our framework, MongoDB as our database, and a package called body-parser to help with JSON requests.

npm install --save express mongodb@2.2.16 body-parser
Copy after login

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

If you run:

npm install --save-dev nodemon
Copy after login

then add the following script to package.json:

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

complete package.json It should look like this:

// package.json
{
  "name": "notable",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "scripts": {
    "dev": "nodemon server.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.15.2",
    "express": "^4.14.0",
    "mongodb": "^2.2.16"
  },
  "devDependencies": {
    "nodemon": "^1.11.0"
  }
}
Copy after login

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

Our server

Start by importing all dependencies in server.js.

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

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

The last thing to do is 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);
});
Copy after login

Now, if you run npm run dev (or node server.js, if you have not installed Nodemon), you should see the prompt "We are live on port 8000" in the terminal.

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

Let’s solve this problem next.

CRUD Routing

For this example, you want to build 4 routes; create note, read note, update note and delete note.

This will give you an idea of ​​how to build almost any basic route using Node.

However, to test your API, you also need to imitate the client to make requests. To do this we will use an excellent app called Postman. It allows you to make simple HTTP requests with custom headers and parameters.

Install Postman and let’s start setting up routing.

Project Structure

Most Node.js tutorials (and many real-life examples) put all routes in one big routes.js file. This makes me a little uncomfortable. In contrast, splitting files into separate folders improves readability and makes large applications easier to manage.

Although we are not doing large-scale applications now, we can still do this. Create the following directory: a app folder, which contains a routes folder, which contains index.js and note_routes.js files.

mkdir app
cd app
mkdir routes
cd routes
touch index.js
touch note_routes.js
Copy after login

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

Your First Route

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

So, before you start, you must first lay the foundation. In Express, the route is contained in a function that takes the Express instance and database as parameters.

Like this:

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

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
};
Copy after login

Then import it for use in server Used in .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);
});
Copy after login

Please note that since the database has not been set up, just 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')
  });
};
Copy after login

When the application receives a post request for the '/notes' path, it will execute the code inside the callback - the request object (contains the request parameters or JSON) and the response object.

You can use Postman to send a POST request to localhost:8000/notes to test.

How to quickly build an API server with Node.js?

你应该得到回复:'Hello'。

太好了!你创建了第一个真正的路由。

下一步是在你的请求中添加一些参数并在 API 中处理它们,最后添加到你的数据库中。

请求参数

在 Postman 中,在选择 x-www-form-urlencoded 单选按钮后,转到 Body 选项卡并添加一些键值对。

这会将编码后的表单数据添加到你的请求中,你可以使用 API ??处理该请求。

How to quickly build an API server with Node.js?

你可以去尝试更多的设置项。

现在在你的 note_routes.js 中,让我们输出 body 的内容。

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

用 Postman 发送请求,你会看到……undefined。

不幸的是,Express 无法自行处理 URL 编码的表单。虽然你确实安装了这个 body-parser 包......

// 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);
});
Copy after login

Now you should see the body as an object in the terminal.
现在你应该将 body 视为终端中的对象。

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

第一个路由的最后一步:设置数据库,然后添加数据。

最简单方法是通过 mLab 设置 Mongo 数据库的:它是最小的而且是免费的,设置的速度非常快。

创建帐户和 MongoDB 部署后,将用户的用户名和密码添加到数据库:

How to quickly build an API server with Node.js?

然后复制这里第二个 URL:

How to quickly build an API server with Node.js?

在项目根目录的目录配置中,创建一个db.js文件。

mkdir config 
cd config
touch db.js
Copy after login

在里面,添加刚才的URL:

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

别忘了把你的用户名和密码(来自数据库用户的密码,而不是你的 mLab 帐户)添加到URL中。 (如果你要将此项目提交到 Github 上,请确保包含 .gitignore 文件 像这样, ,不要与任何人分享你的密码。)

现在在你的 server.js 中,可以用 MongoClient 连接到数据库了,使用它来包装你的应用程序设置:

// 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);
  });               
})
Copy after login

如果你用的是最新版本的 MongoDB(3.0+),请将其修改为:

// 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);
  });               
})
Copy after login

这是你的基础架构的最后一个设置!

添加到你的数据库

MongoDB将数据存储在 collections 中。在你的项目中,你希望将笔记存储在一个名为 notes 的 collection 中。

由于将数据库作为路径中的 db 参数传入,因此可以像这样访问它:

db.collection('notes')
Copy after login

创建笔记就像在集合上调用 insert 一样简单:

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

插入完成后(或由于某种原因失败),要么返回错误或反回新创建的笔记对象。这是完整的 note_routes.js 代码:

// 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]);
      }
    });
  });
};
Copy after login

试试看!使用 Postman 发送 x-www-form-urlencoded POST 请求,在 Body 选项卡下设置 titlebody

响应应如下所示:

How to quickly build an API server with Node.js?

如果你登录mLab,你还应该能够在数据库中看到创建的笔记。

READ 路由

现在可以稍微加快步伐。

假设你希望通过导航到 localhost:8000/notes/{id} 来获取刚创建的笔记。这是链接应该是localhost:8000/notes/585182bd42ac5b07a9755ea3。(如果你没有得到其中笔记的 ID,可以通过检查 mLab 或创建一个新的笔记)。

以下是 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]);
      }
    });
  });
};
Copy after login

就像以前一样,你将在数据库 collection 中调用一个方法。在这里,它被恰当地命名为 findOne。

// note_routes.js
module.exports = function(app, db) {
  app.get('/notes/:id', (req, res) => {
    const details = { '_id': <ID GOES HERE> };
    db.collection(&#39;notes&#39;).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(&#39;notes&#39;).insert(note, (err, result) => {
      if (err) { 
        res.send({ 'error': 'An error has occurred' }); 
      } else {
        res.send(result.ops[0]);
      }
    });
  });
};
Copy after login

你可以通过 req.params.id 从 URL 参数中获取 id。但是,如果你试图将字符串插入上面的 <ID GOES HERE> 位置,它将无法正常工作。

MongoDB 不仅要求 ID 为字符串,还要求 ID 是一个对象,它们被之为 ObjectID。

别担心,这很容易解决。这是完整的代码:

// 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(&#39;notes&#39;).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(&#39;notes&#39;).insert(note, (err, result) => {
      if (err) { 
        res.send({ 'error': 'An error has occurred' }); 
      } else {
        res.send(result.ops[0]);
      }
    });
  });
};
Copy after login

尝试使用一个笔记 ID,它应如下所示:

How to quickly build an API server with Node.js?

DELETE 路由

实际上删除对象与查找对象几乎相同。你只需用 remove 函数替换 findOne 即可。这是完整的代码:

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

UPDATE 路由

最后一个! PUT 方法基本上是 READ 和 CREATE 的混合体。你找到该对象,然后更新它。如果刚才你删除了数据库中唯一的笔记,那就再创建一个!

代码:

// 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(&#39;notes&#39;).update(details, note, (err, result) => {
      if (err) {
          res.send({'error':'An error has occurred'});
      } else {
          res.send(note);
      } 
    });
  });
// ...
Copy after login

现在你可以更新任何笔记,如下所示:

How to quickly build an API server with Node.js?

请注意这些代码还不完美 —— 比如你没有提供正文或标题,PUT 请求将会使数据库中的笔记上的那些字段无效。

API 完成

就这么简单!你完成了可以进行 CRUD 操作的 Node API。

本教程的目的是让你熟悉 Express、Node 和 MongoDB —— 你可以用简单的程序作为进军更复杂项目的跳板。

将来我将会编写系列教程,用不同的语言和框架创建更简单的API。如果你有兴趣,请点击关注!

更多编程相关知识,可访问:编程教学!!

The above is the detailed content of How to quickly build an API server with Node.js?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template