首頁 > web前端 > js教程 > 主體

用Node.js如何快速建構一個API伺服器?

青灯夜游
發布: 2020-09-01 10:00:29
轉載
1957 人瀏覽過

用Node.js如何快速建構一個API伺服器?

Node.js 對初學者來說可能是令人望而卻步的,其靈活的結構和缺乏嚴格的規範使它看起來很複雜。 【影片教學推薦:node js教學 】

本教學是 Node.js,Express 框架和 MongoDB 的快速指南,重點介紹基本的 REST 路由和基本的資料庫互動。你將建立一個簡單的 API 框架模版,然後可以將其用作任何應用。

本教學適用於:你應該對 REST API 和 CRUD 操作有基本的了解,還有基本的 JavaScript 知識。我用的是 ES6(主要是箭頭函數),但不是很複雜。

在本教程中,我們將為創建一個網頁筆記應用的後端骨架—— 類似於Google Keep,能夠執行所有的四個CRUD操作:建立、讀取、更新和刪除。

設定

如果你沒有安裝Node,請參考這裡

建立一個新目錄,執行 npm init,然後按照提示操作,把你的應用程式命名為「notable」(或你可能喜歡的其他名字)。

npm init
登入後複製

一旦完成,在你的目錄中會有一個 package.json 檔案。你可以開始安裝專案所需的依賴項了。

我們將使用 Express 作為自己的框架,MongoDB 作為資料庫,還有一個名為 body-parser 的套件來幫助處理 JSON 請求。

npm install --save express mongodb@2.2.16 body-parser
登入後複製

我還強烈建議將 Nodemon 安裝為 dev 依賴項。這是一個非常簡單的小包,可在檔案更改時自動重新啟動伺服器。

如果你執行:

npm install --save-dev nodemon
登入後複製

然後將以下腳本加入到package.json

// package.json
  "scripts": {
    "dev": "nodemon server.js"
  },
登入後複製

完整的package.json 應如下所示:

// 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"
  }
}
登入後複製

現在,你可以建立server.js 檔案並建立API 了。

我們的伺服器

首先導入 server.js 中的所有相依性。

// server.js
const express        = require('express');
const MongoClient    = require('mongodb').MongoClient;
const bodyParser     = require('body-parser');
const app            = express();
登入後複製

我們將使用 MongoClient 與資料庫互動。也會將應用程式初始化為 Express 框架的實例。

最後一件事就是告訴你的程式開始監聽請求。

你可以指定一個端口,並像這樣開始監聽:

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

現在,如果你執行npm run dev(或node server.js,如果你沒有安裝Nodemon 的話),你應該在終端機中看到「We are live on port 8000」的提示。

你的伺服器已經啟動了。但它現在還什麼也做不了。

接下來讓我們解決這個問題。

CRUD 路由

對於本例,你要建立4條路由; 建立筆記,閱讀筆記,更新筆記和刪除筆記。

這將使你了解如何使用 Node 建立幾乎所有的基本路由。

但是,要測試你的API,還需要模仿客戶端發出請求。為此,我們將使用名為 Postman 的優秀應用程式。它允許你使用自訂的頭和參數進行簡單的 HTTP 請求。

安裝Postman,讓我們開始設定路由。

專案結構

大多數 Node.js 教學(以及許多真實的案例)都將所有路由放在一個很大的 routes.js 檔案中。這讓我有點不舒服。相較之下,將檔案拆成單獨的資料夾可以提高可讀性,並使大型應用程式更易於管理。

雖然我們現在做的不是大型應用,但仍然可以這樣做。建立以下目錄:一個 app 資料夾,裡面有一個routes資料夾,routes 裡面有 index.jsnote_routes.js 檔案。

mkdir app
cd app
mkdir routes
cd routes
touch index.js
touch note_routes.js
登入後複製

對於你的簡單小程式來說,這些目錄可能看起來有些過分,但從一開始就做好總是有意義的。

你的第一個路由

讓我們從 CRUD 中的 C 開始。你將會如何建立一個筆記?

那麼,在你開始之前,必須先打好基礎。在Express中,路由包含在一個函數中,該函數將 Express 實例和資料庫作為參數。

像這樣:

// routes/note_routes.js
module.exports = function(app, db) {
};
登入後複製

然後,你可以透過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
};
登入後複製

然後匯入它以便在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);
});
登入後複製

請注意,由於還沒有設定資料庫,因此只需傳入一個空物件。

好的,現在你可以製作自己的 CREATE 路由了。

語法很簡單:

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

當應用程式收到對'/ notes' 路徑的post 請求時,它將執行回調內的程式碼- request 對象(包含請求的參數或JSON)和response 物件。

你可以使用 Postman 將 POST 請求傳送到 localhost:8000/notes 來測試。

用Node.js如何快速建構一個API伺服器?

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

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

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

请求参数

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

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

用Node.js如何快速建構一個API伺服器?

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

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

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

用 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);
});
登入後複製

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

{ title: 'My Note Title', body: 'What a great note.' }
登入後複製

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

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

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

用Node.js如何快速建構一個API伺服器?

然后复制这里第二个 URL:

用Node.js如何快速建構一個API伺服器?

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

mkdir config 
cd config
touch db.js
登入後複製

在里面,添加刚才的URL:

module.exports = {
  url : YOUR URL HERE
};
登入後複製

别忘了把你的用户名和密码(来自数据库用户的密码,而不是你的 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);
  });               
})
登入後複製

如果你用的是最新版本的 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);
  });               
})
登入後複製

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

添加到你的数据库

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

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

db.collection('notes')
登入後複製

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

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

插入完成后(或由于某种原因失败),要么返回错误或反回新创建的笔记对象。这是完整的 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]);
      }
    });
  });
};
登入後複製

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

响应应如下所示:

用Node.js如何快速建構一個API伺服器?

如果你登录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]);
      }
    });
  });
};
登入後複製

就像以前一样,你将在数据库 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]);
      }
    });
  });
};
登入後複製

你可以通过 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]);
      }
    });
  });
};
登入後複製

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

用Node.js如何快速建構一個API伺服器?

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!');
      } 
    });
  });
// ...
登入後複製

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);
      } 
    });
  });
// ...
登入後複製

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

用Node.js如何快速建構一個API伺服器?

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

API 完成

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

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

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

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

以上是用Node.js如何快速建構一個API伺服器?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:segmentfault.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!