by Niharika Singh
由Niharika Singh
如何在5分鐘內通過身份驗證構建RESTful API —全部從命令行(第1部分) (How to Build a RESTful API with Authentication in 5 minutes — all from your command line (Part 1))
If the title of this article excites you, then my friend, you’re about to achieve level 100 of satisfaction by the end. I’ll quickly go through the course of this article:
如果這篇文章的標題使您興奮,那么我的朋友,您將在最后達到100級的滿意度。 我將快速閱讀本文:
What we are about to create: RESTful API which handles logs of food items on a restaurant menu. The database used in the back-end will be MongoDB. (You can literally use any fricking database on this planet. There’s an exhaustive list of database connectors/non-database connectors supported by LoopBack below.)
我們將要創建的是: RESTful API,該API處理餐廳菜單上食品的日志。 后端使用的數據庫將是MongoDB。 (您實際上可以使用此星球上的任何變形數據庫。下面有LoopBack支持的詳盡的數據庫連接器/非數據庫連接器列表。)
What is LoopBack: In extremely simple terms, it is highly extensible, open source Node.js framework used to create dynamic, end-to-end REST APIs very rapidly. APIs generated via LoopBack are Swagger APIs (world’s most popular API framework, and you’ll see why very soon). The front-end could be made in whichever framework you’re in love with; Angular or React.
什么是LoopBack:簡而言之,它是高度可擴展的開源Node.js框架,用于快速創建動態的端到端REST API。 通過LoopBack生成的API是Swagger API(世界上最流行的API框架,您很快就會看到原因)。 可以在您喜歡的任何框架中創建前端。 角度或React。
Creating application via CLI: This is the WOW part which removes all the programming involved. LoopBack CLI is so beautiful that all the hours of development work are reduced down to seconds. Here, we’d be setting up our database using CLI.
通過CLI創建應用程序:這是WOW部分,它刪除了所有涉及的程序。 LoopBack CLI非常漂亮,以至于所有開發時間都減少到了幾秒鐘。 在這里,我們將使用CLI設置數據庫。
Creating data models via CLI: Again, no programming. All via the beautiful CLI.
通過CLI創建數據模型:同樣,無需編程。 全部通過漂亮的CLI。
Setting up Authentication via CLI: If you have experience creating APIs, you know how tough it is to restrict parts of API using authentication. Setting up token-based authentication using Express+Node.js on the server side is a pain. All of that pain will be taken away by tasting the elixir of LoopBack! It is heaven’s own drink.
通過CLI設置身份驗證:如果您有創建API的經驗,那么您會知道使用身份驗證來限制API的部分是多么困難。 在服務器端使用Express + Node.js設置基于令牌的身份驗證很麻煩。 品嘗LoopBack的長生不老藥,將消除所有這些痛苦! 這是天堂自己的飲料。
分步指南: (Step by Step Guide:)
Pre-requisites: Make sure you’ve got Node.js, Robomongo installed and MongoDB server running.
先決條件:確保已安裝Node.js , Robomongo且MongoDB服務器正在運行。
步驟1:通過NPM安裝LoopBack CLI (STEP 1: Install LoopBack CLI via NPM)
Open the terminal and write the following command to install LoopBack CLI so that ‘lb’ command can be accessed. Only through ‘lb’ command can we generate applications, models, data sources etc. For further reading: https://loopback.io/doc/en/lb2/Command-line-tools.html#using-yeoman
打開終端并輸入以下命令以安裝LoopBack CLI,以便可以訪問“ lb”命令。 只有通過“ lb”命令,我們才能生成應用程序,模型,數據源等。進一步閱讀: https : //loopback.io/doc/en/lb2/Command-line-tools.html#using-yeoman
$ npm install -g loopback-cli
Make sure you install this globally, or else ‘lb’ command might not work for you.
請確保您全局安裝此軟件,否則“ lb”命令可能對您不起作用。
步驟2:建立應用程式 (STEP 2: Creating Application)
Make a directory where you wish to store your project. I’ll name it ‘restaurant-menu’. Make sure you’ve opened this directory in your terminal so that all the files generated via LoopBack are stored in that folder.
創建一個目錄,您要在其中存儲項目。 我將其命名為“餐廳菜單”。 確保已在終端中打開此目錄,以便將通過LoopBack生成的所有文件存儲在該文件夾中。
Then enter the following command:
然后輸入以下命令:
$ lb
A lot of questions will be asked, like those displayed in the image below.
就像下面圖片中顯示的那樣,將會提出很多問題。
(To navigate among options, use arrow keys on your keyboard)
(要在選項之間導航,請使用鍵盤上的箭頭鍵)
API已創建! (THE API IS CREATED!)
I’m not kidding. Don’t believe me? Run the application using the following command:
我不是在開玩笑。 不相信我嗎 使用以下命令運行應用程序:
$ node .
If you point to localhost:3000, you’ll see something like this:
如果您指向localhost:3000,則會看到以下內容:
However, if you go to localhost:3000/explorer, you’ll see the gorgeous SwaggerAPI.
但是,如果您訪問localhost:3000 / explorer,則會看到漂亮的SwaggerAPI。
LoopBack has set up all the routes for you:
LoopBack為您設置了所有路由:
GET users, POST users, PUT users, DELETE users, Login, Log out, Change Password. Literally everything! It would otherwise take hours of work to code this out.
GET用戶,POST用戶,PUT用戶,DELETE用戶,登錄,注銷,更改密碼。 從字面上看一切! 否則,要花費大量時間進行編碼。
Open this folder in any text editor. I’d be using Atom.
在任何文本編輯器中打開此文件夾。 我會使用Atom。
步驟3:連接MongoDB (STEP 3: Connecting MongoDB)
If you open datasources.json
in the Server folder, you should see something like:
如果在Server文件夾中打開datasources.json
,應該會看到類似以下內容的內容:
{ "db": { "name": "db", "connector": "memory" }}
This means that presently, the data source being used is the memory of our computer. We’ve got to change this to Mongo. So let’s install mongo connector:
這意味著當前正在使用的數據源是我們計算機的內存。 我們必須將其更改為Mongo。 因此,讓我們安裝mongo連接器:
$ npm install --save loopback-connector-mongodb
Alongside, I hope mongod is running. This is how you’d know it is running:
同時,我希望mongod正在運行。 這是您如何知道它正在運行的方式:
2018-01-27T15:01:13.278+0530 I NETWORK [thread1] waiting for connections on port 27017
Now, let’s connect the connector!
現在,讓我們連接連接器!
$ lb datasource mongoDS --connector mongoDB
This will ask a lot of questions as follows:
這將提出很多問題,如下所示:
Now modify datasources.json
because we don’t wish to use memory. We wish to use Mongo.
現在修改datasources.json
因為我們不希望使用內存。 我們希望使用Mongo。
{ "db": { "host": "localhost", "port": 27017, "url": "", "database": "food", "password": "", "name": "mongoDS", "user": "", "connector": "mongodb" }}
So our database named: food
is created.
因此,我們創建了名為: food
的數據庫。
步驟4:創建數據模型 (STEP 4: Creating Data Models)
Run following command to create data models:
運行以下命令以創建數據模型:
$ lb model
You may add however many properties to a particular model. To stop entering more properties, just hit Enter to get out of the CLI.
但是,您可以向特定模型添加許多屬性。 要停止輸入更多屬性,只需按Enter鍵即可退出CLI。
Check out dishes.json
in the Common/Models folder.
查看Common / Models文件夾中的dishes.json
。
{ "name": "dishes", "base": "PersistedModel", "idInjection": true, "options": { "validateUpsert": true }, "properties": { "name": { "type": "string", "required": true }, "price": { "type": "number", "required": true } }, "validations": [], "relations": {}, "acls": [], "methods": {}}
You may edit the properties from this json file as well. It is not necessary to use CLI.
您也可以從此json文件編輯屬性。 不需要使用CLI。
Now let’s rerun the server using the following command and head over to localhost:3000/explorer
現在,讓我們使用以下命令重新運行服務器,然后轉到localhost:3000 / explorer
$ node .
Now you’ll see 2 models: dishes
, and user
現在您將看到2個模型: dishes
和user
Now let’s POST some dish
.
現在讓我們發布一些dish
。
Now let’s GET the same dish
.
現在讓我們來做dish
。
You may play around with other HTTP requests too!
您也可以處理其他HTTP請求!
These APIs can be accessed outside the explorer as well:
這些API也可以在資源管理器之外訪問:
http://localhost:3000/api/dishes
http:// localhost:3000 / api / dishes
步驟5:認證:蛋糕上的櫻桃! (STEP 5: AUTHENTICATION: Cherry on the cake!)
To set up authentication, run the following command:
要設置身份驗證,請運行以下命令:
$ lb acl
Now, let’s try to GET the dishes
. Before that, please rerun the server.
現在,讓我們嘗試獲取dishes
。 在此之前,請重新運行服務器。
Let’s get authenticated! For that, we need to get registered first. So we POST in users
.
讓我們通過身份驗證! 為此,我們需要先注冊。 因此我們在users
中users
。
Now, let’s log in.
現在,讓我們登錄。
Now, copy the ID in the response body and paste it in the Access Token field on top of the page.
現在,將ID復制到響應正文中,并將其粘貼到頁面頂部的“訪問令牌”字段中。
Now we are authenticated. YAY.
現在我們已通過身份驗證。 好極了。
Now, let’s GET the dishes
again.
現在,讓我們再次取dishes
。
HOORAY!
哇!
Congratulations if you’ve successfully reached this step. So proud of you.
祝賀您成功完成此步驟。 為你驕傲。
Next steps would be to create a front end around this API which would be done later.
下一步將圍繞該API創建一個前端,稍后再做。
可以在這里找到本文的前端教程。 在該教程中,我使用ReactJS圍繞該API編織了一個前端。 (The frontend tutorial of this article can be found here. In that tutorial, I have used ReactJS to weave a frontend around this API.)
Bye folks! Happy coding.
再見! 快樂的編碼。
翻譯自: https://www.freecodecamp.org/news/build-restful-api-with-authentication-under-5-minutes-using-loopback-by-expressjs-no-programming-31231b8472ca/