当前位置:   article > 正文

node.js编写网页_为Node.js编写可扩展架构

node.js书写基本信息展示页

node.js编写网页

by Zafar Saleem

通过Zafar Saleem

为Node.js编写可扩展架构 (Writing Scalable Architecture For Nodejs)

Writing backend logic for any project these days is pretty easy, thanks to full stack JavaScript. This is especially so with the introduction of dozens of frameworks for both client side and server side implementation.

如今,借助全栈JavaScript,为任何项目编写后端逻辑都非常容易。 随着针对客户端和服务器端实现的数十种框架的引入,尤其如此。

One of the most popular Node.js frameworks is Express.js. It offers an easy approach to building applications at different scales. However, as a project grows, it becomes hard to scale at some point.

Express.js是最受欢迎的Node.js框架之一。 它提供了一种简便的方法来构建不同规模的应用程序。 但是,随着项目的发展,在某个时候很难扩展。

Many developers tend to keep adding new route files and models for new services and API end points. This approach works, but it really makes it hard for future engineers to scale and add new services.

许多开发人员倾向于为新服务和API端点不断添加新的路由文件和模型。 这种方法有效,但是对于将来的工程师来说,确实很难扩展和添加新服务。

In this blog I am going to build a login and registration system that uses JWT authentication with scalable architecture. For those who prefer to get right into the code, go ahead and clone this repository.

在本博客中,我将构建一个使用JWT身份验证和可伸缩体系结构的登录和注册系统。 对于那些喜欢直接使用代码的人,请继续克隆此存储库。

There will be four parts in this blog.

该博客将分为四个部分。

  1. Basic Architecture Setup

    基本架构设置
  2. Registration

    注册
  3. Login

    登录
  4. Dashboard

    仪表板

This blog assumes that you already installed Node.js in your system. Let’s get into the first step — basic architecture setup.

本博客假定您已经在系统中安装了Node.js。 让我们进入第一步-基本架构设置。

基本架构设置 (Basic architecture setup)

First things first, make a new directory on your file system and call it auth (or anything you like).

首先,在文件系统上创建一个新目录,并将其称为auth (或您喜欢的任何名称)。

mkdir auth

Now cd into that directory and create a package.json file. Add the lines below into it.

现在cd到该目录下,并创建一个文件的package.json。 将下面的行添加到其中。

{    "name": "auth",    "version": "0.0.0",    "private": true,    "main": "index.js",    "scripts": {      "start": "node index.js"    },    "dependencies": {      "bcrypt": "latest",      "body-parser": "^1.18.2",      "cookie-parser": "~1.4.3",      "express": "~4.15.5",      "jsonwebtoken": "^8.1.1",      "mongoose": "^5.0.3",      "lodash": "^4.17.11",      "morgan": "^1.9.0",      "passport": "^0.4.0",      "passport-jwt": "^3.0.1",      "serve-favicon": "~2.4.5"    }  }

The most important part of the file above is the dependencies property. These are the dependencies required for the project. They will be used as middleware later in this blog.

上面文件中最重要的部分是dependencies属性。 这些是项目所需的依赖项。 它们将在本博客的后面用作中间件。

Now go ahead and run the command below to install all of these dependencies. You may need to wait a few seconds.

现在继续运行下面的命令来安装所有这些依赖项。 您可能需要等待几秒钟。

npm install

Once it installs all of above dependencies, go ahead and create an index.js file in your root folder, like below:

一旦安装了上述所有依赖项,请继续在根文件夹中创建一个index.js文件,如下所示:

touch index.js

This particular file is only responsible to start the server. To do that, add below code into it:

该特定文件仅负责启动服务器。 为此,将以下代码添加到其中:

'use strict';
const server = require('./server')();const config = require('./configs');const db = require('./configs/db');
server.create(config, db);server.start();

As you can see, this file requires three files:

如您所见,此文件需要三个文件:

  1. server

    服务器
  2. config

    配置
  3. db

    D b

We will create these next.

接下来,我们将创建这些。

The code above then calls the create method on the server module. Finally, it calls the start method, which starts the server.

然后,上面的代码在服务器模块上调用create方法。 最后,它调用start方法,该方法将启动服务器。

1.创建server文件夹 (1. Create the server folder)
mkdir server

Once done, cd into that folder and create another index.js file.

完成后, cd进入该文件夹并创建另一个index.js文件。

touch index.js

Now add the code below into this file:

现在,将以下代码添加到该文件中:

'use strict';
const express = require('express');const bodyParser = require('body-parser');const logger = require('morgan');const mongoose = require('mongoose');const passport = require('passport');const cookieParser = require('cookie-parser');
module.exports = function() {  let server = express(),      create,      start;
create = function(config, db) {      let routes = require('./routes');
// Server settings       server.set('env', config.env);       server.set('port', config.port);       server.set('hostname', config.hostname);
// Returns middleware that parses json       server.use(bodyParser.json());       server.use(bodyParser.urlencoded({ extended: false }));       server.use(cookieParser());       server.use(logger('dev'));       server.use(passport.initialize());       mongoose.connect(db.database);       require('../configs/passport')(passport);
// Set up routes       routes.init(server);   };
start = function() {       let hostname = server.get('hostname'),       port = server.get('port');
server.listen(port, function () {          console.log('Express server listening on - http://' + hostname + ':' + port);        });    };
return {       create: create,       start: start    };};

In this file, we first require all of the dependencies needed for this project. Note that more dependencies can be added into this file whenever required.

在此文件中,我们首先需要此项目所需的所有依赖项。 请注意,可以在需要时将更多依赖项添加到该文件中。

Then we export an anonymous function from this module using module.exports. Inside that function, create three variables: server, create and start.

然后,我们使用module.exports从此模块导出匿名函数。 在该函数内,创建三个变量: servercreatestart

The server variable is for the Express.js server. So, call the express() function and assign that to server. We will assign anonymous functions to the create and start variables.

server变量用于Express.js服务器。 因此,调用express()函数并将其分配给server 。 我们将匿名函数分配给createstart变量。

Now, it is time to write a create function with two parameters: config and db.

现在,该编写具有两个参数的create函数了: configdb

Then set a few server settings using the server.use() function i.e. env, port and hostname. Then use cookieParser, bodyParser, logger and passport middlewares. Then connect to mongoose database and finally require passport’s configuration file and call it with the required passport.

然后使用server.use()函数设置一些服务器设置,即env,端口和主机名。 然后使用cookieParser, bodyParser, logger and passport中间件。 然后连接到mongoose数据库,最后要求提供护照的配置文件,并使用所需的护照进行调用。

Passport middleware is used for authentication, which we will use later in this blog. To learn more about it click here.

Passport中间件用于身份验证,我们将在本博客的后面部分中使用它。 要了解更多信息,请单击此处

Now it’s time for API end points i.e. routes. Simply call the init function on routes and pass server into this.

现在是时候使用API​​端点了,即路由。 只需在路由上调用init函数并将server传递给它即可。

Next, write the start function. Set hostname and port and start the server with the listen command inside this function.

接下来,编写start功能。 设置hostnameport ,然后在此函数中使用listen命令启动服务器。

Then, return both create and start functions to make them available for other modules to use.

然后,返回createstart函数,以使它们可供其他模块使用。

2.创建配置文件夹 (2. Create the config folder)

At the root level, create a configs folder:

在根级别,创建一个configs文件夹:

mkdir configs

cd into that folder and create an index.js file:

cd进入该文件夹并创建一个index.js文件:

touch index.js

Add the below code to the index.js file:

将以下代码添加到index.js文件:

'use strict';
const _ = require('lodash');const env = process.env.NODE_ENV || 'local';const envConfig = require('./' + env);
let defaultConfig = {  env: env};
module.exports = _.merge(defaultConfig, envConfig);

Now create a local.js file:

现在创建一个local.js文件:

touch local.js

Open it, and add the code below:

打开它,并添加以下代码:

'use strict';
let localConfig = {  hostname: 'localhost',  port: 3000};
module.exports = localConfig;

This one’s simple too. We are creating a localConfig object and adding a few properties such as hostname and port. Then export it to use it like we are doing in the ./index.js file.

这也很简单。 我们正在创建一个localConfig对象,并添加了一些属性,例如hostnameport 。 然后将其导出以像在./index.js文件中一样使用它。

3.现在创建一个数据库 (3. Now create a database)
touch db.js

Open db.js in your favourite editor and paste the below code into it.

在您喜欢的编辑器中打开db.js并将以下代码粘贴到其中。

module.exports = {   'secret': 'putsomethingsecretehere',  'database': 'mongodb://127.0.0.1:27017/formediumblog'};

We are exporting a JavaScript object with properties secret and database. These are used to connect with a MongoDB database using middleware called mongoose.

我们正在导出具有secretdatabase属性JavaScript对象。 这些用于使用称为mongoose的中间件与MongoDB数据库连接。

构建应用 (Building the app)

Now we are done with basic setup of our project, time for the fun stuff!

现在,我们完成了项目的基本设置,花点时间玩了!

cd into the server folder and create the following folders:

cd进入server文件夹并创建以下文件夹:

mkdir controllers models routes services

First, we will cover the routes folder. This folder is used to add all the end points that are available for client side use. First of all go ahead and create the index.js file first inside the routes folder.

首先,我们将介绍routes文件夹。 此文件夹用于添加可用于客户端的所有端点。 首先,首先在routes文件夹内创建index.js文件。

touch index.js

And put the below code into this file:

并将以下代码放入此文件:

'use strict';
const apiRoute = require('./apis');
function init(server) {  server.get('*', function (req, res, next) {    console.log('Request was made to: ' + req.originalUrl);    return next();  });
server.use('/api', apiRoute);}
module.exports = {  init: init};

First, require the apiRoute folder which we are going to create next. This folder will contain another folder with the version number of the API i.e. v1 .

首先,要求我们接下来要创建的apiRoute文件夹。 该文件夹将包含具有API版本号即v1另一个文件夹。

Second create an init function. We are calling this function from the server/index.js file inside the create function at the bottom and passing server as a parameter. It simply gets all the routes and returns the next callback function.

其次创建一个init函数。 我们从底部create函数中的server/index.js文件中调用此函数,并将server作为参数传递。 它只是获取所有路由并返回下一个回调函数。

Then use the apiRoute that we are requiring above. Finally, export the init function to make this function available in the rest of the project.

然后使用上面需要的apiRoute 。 最后,导出init函数,以使其在项目的其余部分中可用。

Now go ahead create an apis folder. Inside that folder create a file index.js .

现在继续创建一个apis文件夹。 在该文件夹中,创建一个文件index.js

mkdir apistouch index.js

Paste the below code into the index.js file.

将以下代码粘贴到index.js文件中。

'use strict';
const express = require('express');const v1ApiController = require('./v1');
let router = express.Router();
router.use('/v1', v1ApiController);
module.exports = router;

This file requires express and the api version folder i.e. v1. Then create the router and make /v1 end point using router.use() method. Finally export the router.

该文件需要express和api版本文件夹,即v1 。 然后创建路由器,并使用router.use()方法创建/v1端点。 最后导出路由器。

It’s time to create apis/v1.js file. Paste the below code inside the v1.js file:

是时候创建apis/v1.js文件了。 将以下代码粘贴到v1.js文件中:

'use strict';
const registerController = require('../../controllers/apis/register');const express = require('express');
let router = express.Router();
router.use('/register', registerController);
module.exports = router;

We need to register the controller and express.js and create a router. Then we need to expose register API endpoints for client side use. Finally, we must export the router from this module.

我们需要注册控制器和express.js并创建一个路由器。 然后,我们需要公开register API端点供客户端使用。 最后,我们必须从该模块导出路由器。

This is the file that we are going to keep modifying. We will require more controllers here when we create them.

这是我们将继续修改的文件。 创建它们时,我们将在此处需要更多的控制器。

Now we are done with the routes folder, and it is time for the controllers folder. Go ahead and CD into that folder and create a folder apis .

现在我们完成了routes文件夹,现在该到controllers文件夹了。 继续,将CD放入该文件夹并创建一个文件夹apis

mkdir apis

Now that we have the apis folder inside controllers, we are going to create the following three controllers and their respective services.

现在,我们在controllers有apis文件夹,我们将创建以下三个控制器及其各自的services

  1. Basic Architecture Setup

    基本架构设置
  2. Registration

    注册

  3. Login

    登录
  4. Dashboard

    仪表板

First up is the registerController. Go ahead and create the below file.

首先是registerController 。 继续并创建以下文件。

touch register.js

Open this file in your favourite editor and paste the below code into it:

在您喜欢的编辑器中打开此文件,并将以下代码粘贴到其中:

'use strict';
const express = require('express');const registerService = require('../../services/authentication/register');
let router = express.Router();
router.post('/', registerService.registerUser);
module.exports = router;

First it is requiring express.js and the register service (which we are going to write later). Then create a router using the express.Router() method and make a post request to the '/' path. Then call the registerUser method on registerService (which we are going to write later). Finally, export the router from this module.

首先,它需要express.jsregister服务(我们将在稍后编写)。 然后使用express.Router()方法创建一个路由器,并向'/'路径发出发布请求。 然后在registerService上调用registerUser方法(我们将在稍后编写)。 最后,从该模块导出路由器。

Now we need to require this controller inside the routes/apis/v1.js file which we already did.

现在,我们需要在已经完成的routes/apis/v1.js文件中要求此控制器。

Now registering the controller is done. It is time to get to the services folder. CD into that folder and create an authentication folder. First things first, cd into authentication and create a register.js file.

至此,控制器注册完成。 现在是时候进入services文件夹了。 将CD放入该文件夹并创建一个authentication文件夹。 首先,cd进入authentication并创建一个register.js文件。

touch register.js

Then open the register.js file and paste the below code into it:

然后打开register.js文件,并将以下代码粘贴到其中:

'use strict';
const express = require('express');const User = require('../../models/User');
const httpMessages = {  onValidationError: {    success: false,    message: 'Please enter email and password.'  },  onUserSaveError: {    success: false,    message: 'That email address already exists.'  },  onUserSaveSuccess: {    success: true,    message: 'Successfully created new user.'  }}
// Register new usersfunction registerUser(request, response) {  let { email, password } = request.body;
if (!email || !password) {    response.json(httpMessages.onValidationError);  } else {    let newUser = new User({      email: email,      password: password    });
// Attempt to save the user    newUser.save(error => {      if (error) {        return response.json(httpMessages.onUserSaveError);      }      response.json(httpMessages.onUserSaveSuccess);    });  }}
module.exports = {  registerUser: registerUser};

In the register service, first we are requiring expressjs and User model. Then we are creating a JavaScript object i.e. httpMessages which is basically a list of all the messages we are going to send to clients via the api when the client sends the request.

register服务中,首先我们需要expressjsUser模型。 然后,我们创建一个JavaScript对象,即httpMessages ,它基本上是当客户端发送请求时我们将通过api发送给客户端的所有消息的列表。

Then the function registerUser which actually performs the registration process. Before saving the user there is a check if the user provided their email and password. If they did then create a newUser using the new keyword with the provided email and password.

然后,函数registerUser实际执行注册过程。 保存用户之前,需要检查用户是否提供了他们的电子邮件和密码。 如果他们这样做,则使用带有提供的电子邮件和密码的new关键字创建一个newUser。

Then simply call the save function on newUser to save that user in the database and send the appropriate response using response.json.

然后只需在newUser上调用save函数将该用户保存在数据库中,并使用response.json发送适当的response.json

Finally export this function using module.exports to make use of it in the rest of the project. We are using this inside the controllers/register.js file.

最后,使用module.exports导出此函数以在项目的其余部分中使用它。 我们在controllers/register.js文件中使用它。

Before testing this to see if it works, first we need to create a User model. Go ahead create a file User.js inside the models folder.

在测试它是否可行之前,首先我们需要创建一个User模型。 继续在models文件夹中创建一个文件User.js

touch User.js

And paste this code into the above file:

并将此代码粘贴到上面的文件中:

const mongoose = require('mongoose');const bcrypt = require('bcrypt');
const UserSchema = new mongoose.Schema({  email: {    type: String,    lowercase: true,    unique: true,    required: true  },  password: {    type: String,    required: true  },  role: {    type: String,    enum: ['Client', 'Manager', 'Admin'],    default: 'Client'  }});
UserSchema.pre('save', function(next) {  let user = this;
if (this.isModified('password') || this.isNew) {      bcrypt.genSalt(10, (err, salt) => {        if (err) {          console.log(err);          return next(err);        }
bcrypt.hash(user.password, salt, (err, hash) => {          if (err) {            console.log(err);            return next(err);          }
user.password = hash;          next();        });      });  } else {    return next();  }});
// Create method to compare password input to password saved in databaseUserSchema.methods.comparePassword = function(pw, cb) {  bcrypt.compare(pw, this.password, function(err, isMatch) {    if (err) {      return cb(err);    }
cb(null, isMatch);  });};
module.exports = mongoose.model('User', UserSchema);

First of all require the mongoose and bcrypt modules. Mongoose is used to create mongodb schema whereas bcrypt is used to encrypt passwords before storing them into the database.

首先需要mongoosebcrypt模块。 Mongoose用于创建mongodb模式,而bcrypt用于在将密码存储到数据库之前对其进行加密。

Create UserSchema with email, password and role properties. Then before saving the user, perform some checks before hashing the password.

使用email, password and role属性创建UserSchema 。 然后,在保存用户之前,请先进行一些检查,然后再对密码进行哈希处理。

The final function is to compare the passwords. It compares the user’s password with the hashed password in the database.

最后的功能是比较密码。 它将用户密码与数据库中的哈希密码进行比较。

Now in order to test this code, open postman (if you haven’t installed postman go ahead install it from here). Open postman and enter the below url:

现在,为了测试该代码,请打开postman(如果尚未安装postman,请从此处开始安装它)。 打开邮递员,然后输入以下网址:

http://localhost:3000/api/v1/register

Select POST as the request, choose the body tab and form-urlencoded and enter the email and password. Press the send button and you should see the below success message.

选择“ POST”作为请求,选择“ body”选项卡并进行form-urlencoded然后输入电子邮件和密码。 按下发送按钮,您将看到以下成功消息。

Now the register part is done.

现在注册部分完成了。

  1. Basic Architecture Setup

    基本架构设置
  2. Register

    寄存器
  3. Login

    登录

  4. Dashboard

    仪表板

It is time to focus on login. Create a login.js file inside the controllers folder.

现在该专注于登录了。 在controllers文件夹中创建一个login.js文件。

touch login.js

Now open it and paste the below code:

现在打开它并粘贴以下代码:

'use strict';
const express = require('express');const loginService = require('../../services/authentication/login');
let router = express.Router();
router.post('/', loginService.loginUser);
module.exports = router;

Again it’s simple and the same as the register module: after importing express.js and loginService we are creating the router and make a post request to the root path '/' with the loginUser callback function on loginService . Finally export the router.

此外它的简单,一样的寄存器模块:导入后express.jsloginService ,我们正在创建的路由器,使POST请求根路径'/'loginUser的回调函数loginService 。 最后导出路由器。

It’s time to require loginController in the routes/apis/v1.js file. Your v1.js file should look like the below now.

现在是时候在routes/apis/v1.js文件中要求loginController了。 您的v1.js文件现在应该如下所示。

'use strict';
const registerController = require('../../controllers/apis/register');const loginController = require('../../controllers/apis/login');
const express = require('express');
let router = express.Router();
router.use('/register', registerController);router.use('/login', loginController);
module.exports = router;

Now for the login service, create a login.js file inside services/authentication/:

现在为登录服务,在services/authentication/创建一个login.js文件:

touch login.js

And paste the below code into this file:

并将以下代码粘贴到该文件中:

'use strict';
const express = require('express');const apiRoutes = express.Router();
const jwt = require('jsonwebtoken');const passport = require('passport');const db = require('../../../configs/db');
const User = require('../../models/User');
const httpResponse = {  onUserNotFound: {    success: false,    message: 'User not found.'  },  onAuthenticationFail: {    success: false,    message: 'Passwords did not match.'  }}
function loginUser(request, response) {   let { email, password } = request.body;
User.findOne({    email: email  }, function(error, user) {    if (error) throw error;
if (!user) {      return response.send(httpResponse.onUserNotFound);    }
// Check if password matches    user.comparePassword(password, function(error, isMatch) {      if (isMatch && !error) {        var token = jwt.sign(user.toJSON(), db.secret, {           expiresIn: 10080        });
return response.json({           success: true, token: 'JWT ' + token        });      }
response.send(httpResponse.onAuthenticationFail);    });  });};
module.exports = {  loginUser: loginUser};

First require some necessary modules such as: express.js, jsonwebtoken, passport, db and User model. Create a JavaScript object that has a list of messages to be sent to the client side when the http request is made to this service.

首先需要一些必要的模块,例如: express.js, jsonwebtoken, passport, db and User model 。 创建一个JavaScript对象,该对象具有向此服务发出http请求时要发送到客户端的消息列表。

Create a loginUser function, and inside that create a couple of variables i.e. email and password, and assign the email and password sent by the user to these variables which are in request.body.

创建一个loginUser函数,并在其中创建几个变量,例如email和password,并将用户发送的电子邮件和密码分配给request.body这些变量。

Then use the findOne() method on the User model to find a use based on the email sent from the client by the user. The callback function of findOne() accepts 2 parameters, error and user. First check if the above findOne() method throws any error — if it does then throw an error.

然后,在User模型上使用findOne()方法根据User从客户端发送的电子邮件查找用途。 findOne()的回调函数接受2个参数, error and user 。 首先检查上面的findOne()方法是否引发任何错误-如果确实引发了错误。

Then perform a check: if no user is found, then send the proper response with a message from the list of messages that we declared above in this module.

然后执行检查:如果未找到用户,则发送适当的响应,并从上面我们在此模块中声明的消息列表中发送一条消息。

Then compare the password that the user sent with the one in the database using the compare function we wrote in the User model earlier in this blog.

然后,使用我们在本博客前面的User模型中编写的compare函数,将用户发送的密码与数据库中的密码compare

If the password matches and it does not return an error, then we create a token using the jsonwebtoken module and return that token using json.response() to the client. Otherwise we send an authenticationFail message.

如果密码匹配并且没有返回错误,则我们使用jsonwebtoken模块创建一个令牌,然后使用json.response()将该令牌返回给客户端。 否则,我们会发送一个authenticationFail消息。

Finally export the loginUser function with exports.module so that we can use it in our controllers and anywhere else.

最后导出loginUser与功能exports.module这样我们就可以在我们的控制器使用它和其他任何地方。

It’s time to test login functionality. Go back to postman and this time replace register with login as the api end point in the url. Enter the email and password and press the send button. You should be able to receive a token. Go ahead and copy that to the clipboard because you will use it later to access the dashboard.

现在该测试登录功能了。 回到邮递员,这次更换registerlogin在URL中的API终点。 输入电子邮件和密码,然后按发送按钮。 您应该能够收到令牌。 继续并将其复制到剪贴板,因为稍后将使用它来访问仪表板。

  1. Basic Architecture Setup

    基本架构设置
  2. Register

    寄存器
  3. Login

    登录
  4. Dashboard

    仪表板

Now it’s time for the dashboard.js file. Create dashboard.js file insidecontrollers folder.

现在到了dashboard.js文件的时候了。 在controllers文件夹中创建dashboard.js文件。

touch dashboard.js

And open it and paste the below code:

并将其打开并粘贴以下代码:

'use strict';
const passport = require('passport');const express = require('express');const dashboardService = require('../../services/dashboard/dashboard');
let router = express.Router();
router.get('/', passport.authenticate('jwt', { session: false }), dashboardService.getDashboard);
module.exports = router;

This controller is different in the sense that it requires authenticated access. That is, only a logged-in user can access the dashboard service and make different http requests.

该控制器在某种意义上是不同的,它需要经过身份验证的访问。 也就是说,只有登录的用户才能访问仪表板服务并发出不同的http请求。

For that reason we are also importing passport, and for the get request we are using the passport.authenticate() function to getDashboard service.

出于这个原因,我们也导入了护照,对于获取请求,我们正在使用passport.authenticate()函数获取getDashboard服务。

Again we need to require dashboardController in the routes/apis/v1.js file. Your v1.js file should look like the below:

同样,我们需要在routes/apis/v1.js文件中要求dashboardController 。 您的v1.js文件应如下所示:

'use strict';
const registerController = require('../../controllers/apis/register');const loginController = require('../../controllers/apis/login');const dashboardController = require('../../controllers/apis/dashboard');
const express = require('express');
let router = express.Router();
router.use('/register', registerController);router.use('/login', loginController);router.use('/dashboard', dashboardController);
module.exports = router;

Now that dashboardController is available to be used for client side requests, it’s time to create its respective service. Go to the services folder and create a dashboard folder inside it. Create a dashboard.js file and put the below code inside this file.

现在, dashboardController可用于客户端请求,是时候创建其各自的服务了。 转到services文件夹并在其中创建一个dashboard文件夹。 创建一个dashboard.js文件,并将以下代码放入该文件中。

'use strict';
function getDashboard(request, response) {  response.json('This is from dashboard');}
module.exports = {  getDashboard: getDashboard}

No fancy stuff going on. For demonstration purposes, I am simply responding with a text message This is from dashboard. Then export this method to be used in its respective controller which we already accomplished.

没有花哨的东西继续。 出于演示目的,我仅以文本消息“ This is from dashboard响应。 然后导出此方法以在我们已经完成的相应控制器中使用。

Now it’s testing time. Open postman and change the end point of the url to the dashboard. Click the headers tab and add Authorization and paste the JTW copied in the previous step when you logged in.

现在是测试时间。 打开邮递员,然后将URL的终点更改为仪表板。 单击标题选项卡并添加Authorization并粘贴登录时在上一步中复制的JTW。

You should see the message This is from dashboard as a response.

您应该看到消息“ This is from dashboard作为响应。

As you can see, when we make a new service we need one controller for it and we can keep adding new services into the architecture. If you would like to change the version of the API and also keep the current one, simply add a new v2.js file and redirect all requests to that end point. That is one simple example.

如您所见,当我们提供新服务时,我们需要一个控制器,并且可以继续向架构中添加新服务。 如果您想更改API的版本并保留当前版本,只需添加一个新的v2.js文件并将所有请求重定向到该端点即可。 那是一个简单的例子。

I hope you liked this blog and see you next time.

希望您喜欢这个博客,下次再见。

UPDATE: If you would like to implement its client side then please click here where I used react.js to authenticate with this server.

更新:如果您想实现其客户端,请单击此处我使用react.js对此服务器进行身份验证的位置。

翻译自: https://www.freecodecamp.org/news/writing-scalable-architecture-for-node-js-2b58e0523d7f/

node.js编写网页

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/118828
推荐阅读
相关标签
  

闽ICP备14008679号