国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

30分鐘用Node.js構建一個API服務器的步驟詳解

2019-11-19 11:28:36
字體:
來源:轉載
供稿:網友

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.jsconst express    = require('express');const MongoClient  = require('mongodb').MongoClient;const bodyParser   = require('body-parser');const app      = express();

我們將使用 MongoClient 與數據庫進行交互。還會將應用初始化為 Express 框架的實例。

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

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

// server.jsconst 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 appcd appmkdir routescd routestouch index.jstouch note_routes.js

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

你的第一個路由

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

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

像這樣:

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

然后,你可以通過 index.js 導出此函數:

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

然后導入它以便在 server.js 中使用:

// server.jsconst 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.jsmodule.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 來測試。

你應該得到回復:'Hello'。

太好了!你創建了第一個真正的路由。

下一步是在你的請求中添加一些參數并在 API 中處理它們,最后添加到你的數據庫中。

請求參數

在 Postman 中,在選擇 x-www-form-urlencoded 單選按鈕后,轉到 Body 選項卡并添加一些鍵值對。

這會將編碼后的表單數據添加到你的請求中,你可以使用 API ​​處理該請求。

你可以去嘗試更多的設置項。

現在在你的 note_routes.js 中,讓我們輸出 body 的內容。

// note_routes.jsmodule.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 部署后,將用戶的用戶名和密碼添加到數據庫:

然后復制這里第二個 URL:

在項目根目錄的目錄配置中,創建一個db.js文件。

mkdir config cd configtouch db.js

在里面,添加剛才的URL:

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

別忘了把你的用戶名和密碼(來自數據庫用戶的密碼,而不是你的 mLab 帳戶)添加到URL中。 (如果你要將此項目提交到 Github 上,請確保包含 .gitignore 文件 像這樣,,不要與任何人分享你的密碼。)

現在在你的 server.js 中,可以用 MongoClient 連接到數據庫了,使用它來包裝你的應用程序設置:

// server.jsconst 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.jsconst 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.jsmodule.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

響應應如下所示:

如果你登錄mLab,你還應該能夠在數據庫中看到創建的筆記。

READ 路由

現在可以稍微加快步伐。

假設你希望通過導航到 localhost:8000/notes/{id} 來獲取剛創建的筆記。這是鏈接應該是localhost:8000/notes/585182bd42ac5b07a9755ea3。(如果你沒有得到其中筆記的 ID,可以通過檢查 mLab 或創建一個新的筆記)。

以下是 note_routes.js 中的內容:

// note_routes.jsmodule.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.jsmodule.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]);   }  }); });};

你可以通過 req.params.id 從 URL 參數中獲取 id。但是,如果你試圖將字符串插入上面的 <ID GOES HERE> 位置,它將無法正常工作。

MongoDB 不僅要求 ID 為字符串,還要求 ID 是一個對象,它們被之為 ObjectID。

別擔心,這很容易解決。這是完整的代碼:

// note_routes.jsvar 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]);   }  }); });};

嘗試使用一個筆記 ID,它應如下所示:

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

現在你可以更新任何筆記,如下所示:

請注意這些代碼還不完美 ―― 比如你沒有提供正文或標題,PUT 請求將會使數據庫中的筆記上的那些字段無效。

API 完成

就這么簡單!你完成了可以進行 CRUD 操作的 Node API。

本教程的目的是讓你熟悉 Express、Node 和 MongoDB ―― 你可以用簡單的程序作為進軍更復雜項目的跳板。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 洛南县| 桦甸市| 恩施市| 汽车| 安龙县| 嘉禾县| 禄丰县| 西畴县| 四平市| 开阳县| 公主岭市| 康定县| 上虞市| 安岳县| 宁陵县| 墨脱县| 长岛县| 南江县| 临江市| 上蔡县| 水城县| 永州市| 芦山县| 巩留县| 达孜县| 定南县| 东乡族自治县| 遵化市| 德令哈市| 晋宁县| 肇庆市| 寿宁县| 西昌市| 海城市| 工布江达县| 九江县| 彭泽县| 镇坪县| 邳州市| 登封市| 平遥县|