如何在5分钟内通过身份验证构建RESTful API —全部从命令行(第1部分)

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级的满意度。 我将快速阅读本文:

  1. 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支持的详尽的数据库连接器/非数据库连接器列表。)

  2. 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。

  3. 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设置数据库。

  4. Creating data models via CLI: Again, no programming. All via the beautiful CLI.

    通过CLI创建数据模型:同样,无需编程。 全部通过漂亮的CLI。

  5. 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.jsRobomongo且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个模型: dishesuser

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.

让我们通过身份验证! 为此,我们需要先注册。 因此我们在usersusers

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/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值