mysql桌面应用程序_如何使用AdonisJs和MySQL构建鼓舞人心的报价应用程序

news/2024/7/3 6:42:10

mysql桌面应用程序

The author selected the Tech Education Fund to receive a donation as part of the Write for DOnations program.

作者选择了Tech Education Fund作为“ Write for DOnations”计划的一部分来接受捐赠。

介绍 (Introduction)

AdonisJs is a Node.js web framework written in plain JavaScript that runs on all major operating systems. It uses the popular MVC (Model - View - Controller) design pattern and offers a stable ecosystem for writing server-side web applications. The framework features seamless authentication, SQL ORM (object-relational mapping), migrations, and database seeding. AdonisJs has a similar architecture to the PHP web application framework Laravel, including the same folder structure and several shared setup concepts.

AdonisJs是用纯JavaScript编写的Node.js Web框架,可在所有主要操作系统上运行。 它使用流行的MVC(模型-视图-控制器)设计模式,并为编写服务器端Web应用程序提供了稳定的生态系统。 该框架具有无缝身份验证 ,SQL ORM(对象关系映射), 迁移和数据库种子的功能 。 AdonisJs具有相似的结构PHP web应用框架Laravel ,包括相同的文件夹结构和多个共享设置理念。

By default, AdonisJs uses the Edge template engine that is designed for intuitive use. Just like Laravel, AdonisJs ships with an ORM called Lucid that serves as an interface for communication between an application’s models and the database. With AdonisJs, developers can build a full-stack application where the back-end server will be responsible for applying the business logic, routing, and rendering all the pages for the application. It is also possible to create a web service API to return JSON responses from a controller; these web services can then be consumed using front-end frameworks such as Vue.js, React, and Angular.

默认情况下,AdonisJs使用为直观使用而设计的Edge模板引擎 。 就像Laravel一样,AdonisJs附带有一个称为Lucid的ORM,该ORM充当应用程序模型与数据库之间的通信接口。 借助AdonisJs,开发人员可以构建一个全栈应用程序,后端服务器将负责应用业务逻辑,路由并呈现该应用程序的所有页面。 还可以创建一个Web服务API来从控制器返回JSON响应。 然后可以使用诸如Vue.js , React和Angular的前端框架来使用这些Web服务。

In this tutorial, you’ll build an application with AdonisJs using its CLI. You’ll create routes, controllers, models, and views within your application and you’ll carry out form validations. The example in this tutorial will be an inspirational quote application in which a user can sign up and log in to create an inspirational quote. This demo application will give you the opportunity to carry out CRUD (Create, Read, Update, and Delete) operations.

在本教程中,您将使用其CLI使用AdonisJs构建应用程序。 您将在应用程序内创建路线,控制器,模型和视图,并进行表单验证。 本教程中的示例将是一个鼓舞人心的报价应用程序,用户可以在其中注册并登录以创建鼓舞人心的报价。 该演示应用程序将使您有机会执行CRUD(创建,读取,更新和删除)操作。

先决条件 (Prerequisites)

Before you begin this guide, you will need the following:

在开始本指南之前,您需要满足以下条件:

  • A local installation of Node.js (at least v8) and npm (at least v3.0). Node.js is a JavaScript run-time environment that allows you to run your code outside of the browser. It comes with a pre-installed package manager called npm, which lets you install and update packages. To install these on macOS or Ubuntu 18.04, follow the steps in How to Install Node.js and Create a Local Development Environment on macOS or the Installing Using a PPA section of How To Install Node.js on Ubuntu 18.04.

    Node.js (至少v8)和npm (至少v3.0)的本地安装。 Node.js是一个JavaScript运行时环境,可让您在浏览器之外运行代码。 它带有一个预安装的软件包管理器npm,可让您安装和更新软件包。 要将它们安装在macOS或Ubuntu 18.04上,请遵循如何在macOS上安装Node.js并创建本地开发环境中的步骤,或如何在Ubuntu 18.04上安装Node.js的 使用PPA安装部分中的步骤 。

  • MySQL installed on your machine. Follow the instructions here to download and install it for your choice of the operating system. To successfully install MySQL, you can either install it by using Homebrew on Mac or for Ubuntu 18.04 follow our tutorial How To Install MySQL on Ubuntu 18.04.

    在您的计算机上安装了MySQL。 请按照此处的说明下载并安装该操作系统,以供您选择操作系统。 要成功安装MySQL,可以在Mac上使用Homebrew进行安装,也可以在Ubuntu 18.04上进行安装,请按照我们的教程如何在Ubuntu 18.04上安装MySQL进行操作 。

  • A basic understanding of JavaScript; see our How To Code in JavaScript series.

    对JavaScript有基本了解; 请参阅我们的“ 如何使用JavaScript编码”系列。

  • A text editor installed, such as Visual Studio Code, Atom, or Sublime Text.

    已安装的文本编辑器,例如Visual Studio Code , Atom或Sublime Text 。

Note: This tutorial uses a macOS machine for development. If you’re using another operating system, you may need to use sudo for npm commands in the first steps.

注意:本教程使用macOS机器进行开发。 如果您使用的是其他操作系统,则在第一步中可能需要将sudo用于npm命令。

第1步-安装Adonis CLI (Step 1 — Installing the Adonis CLI)

In this section, you will install Adonis CLI and all its required packages on your local machine. The CLI will allow you to scaffold a new AdonisJs project as well as create and generate boilerplate for controllers, middlewares, and models in your application. You’ll also create your database for the project.

在本节中,您将在本地计算机上安装Adonis CLI及其所有必需的软件包。 该CLI将允许您构建一个新的AdonisJs项目,并为应用程序中的控制器,中间件和模型创建并生成样板。 您还将为项目创建数据库。

Run the following command to install the AdonisJs CLI globally on your machine via npm:

运行以下命令,以通过npm在您的计算机上全局安装AdonisJs CLI:

  • npm i -g @adonisjs/cli

    npm我-g @ adonisjs / cli

Once the installation process is complete, type the following command in the terminal to confirm the installation of AdonisJs and view the current version:

安装过程完成后,在终端中键入以下命令以确认AdonisJs的安装并查看当前版本:

  • adonis --version

    阿多尼斯--version

You will see output showing the current version of AdonisJs:

您将看到输出,显示当前版本的AdonisJs:


   
Output
4.1.0

With the successful installation of the AdonisJs CLI, you now have access to and can use the adonis command to create fresh installations of an AdonisJs project, manage your project, and generate relevant files such as the controllers, models, etc.

成功安装AdonisJs CLI后,您现在可以访问并可以使用adonis命令创建AdonisJs项目的全新安装,管理您的项目并生成相关文件,例如控制器,模型等。

Now, you can proceed to create a new AdonisJs project by using the adonis command as shown here:

现在,您可以使用adonis命令继续创建一个新的AdonisJs项目,如下所示:

  • adonis new adonis-quotes-app

    阿多尼斯新阿多尼斯报价应用

The preceding command will create an application named adonis-quotes-app in a new directory with the same name in your local project directory with the relevant AdonisJs MVC structure.

前面的命令将在新目录中创建一个名为adonis-quotes-app ,该adonis-quotes-app在本地项目目录中具有相同的名称,并具有相关的AdonisJs MVC结构。

Move into the new application folder:

移至新的应用程序文件夹:

  • cd adonis-quotes-app

    cd adonis-quotes-app

Then start your application by running:

然后运行以下命令启动应用程序:

  • adonis serve --dev

    阿多尼斯服务--dev

This will start the development server on the default port 3333 as specified inside the root .env file for your application. Navigate to http://localhost:3333 to view the welcome page of AdonisJs.

这将在应用程序的根.env文件内指定的默认端口3333上启动开发服务器。 导航到http:// localhost:3333以查看AdonisJs的欢迎页面。

Now you’ll complete the setup of your database. Here, you’ll install the mysql driver to connect to your MySQL server from your Node.js application via npm. To begin, go back to your terminal where the application is currently running, stop the process with CTRL + C and run the following command:

现在,您将完成数据库的设置。 在这里,您将安装mysql驱动程序 ,以通过npm从Node.js应用程序连接到MySQL服务器。 首先,返回到您的当前正在运行应用程序的终端,使用CTRL + C停止该过程并运行以下命令:

  • npm i mysql

    NPM我MySQL

Now that you have successfully installed the MySQL Node.js driver for this application, you need to create the application database and set up the appropriate connection to it.

现在,您已经成功为该应用程序安装了MySQL Node.js驱动程序,您需要创建应用程序数据库并建立与其的适当连接。

The latest version of MySQL that you have installed from the prerequisite tutorial uses a default authentication plugin named caching_sha2_password. This is currently not supported by Node.js drivers for MySQL. To avoid any database connection issue from your application, you will need to create a new MySQL user and use the currently supported authentication plugin—mysql_native_password.

在先决条件教程中安装的最新版本MySQL使用名为caching_sha2_password的默认身份验证插件。 MySQL的Node.js驱动程序当前不支持此功能。 为了避免应用程序出现任何数据库连接问题,您将需要创建一个新MySQL用户并使用当前支持的身份验证插件mysql_native_password

To begin, access the MySQL client using the root account:

首先,使用root帐户访问MySQL客户端:

  • mysql -u root -p

    mysql -u root -p

You will be prompted to enter your root account password set up during the MySQL installation.

系统将提示您输入在MySQL安装过程中设置的root帐户密码。

Next, create the user and password using the mysql_native_password plugin:

接下来,使用mysql_native_password插件创建用户和密码:

  • CREATE USER 'sammy'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';

    创建用户' sammy '@'localhost'用mysql_native_password通过' password '标识;

You will see the following output:

您将看到以下输出:


   
Output
Query OK, 0 rows affected (0.02 sec)

Next, create a database for the application with:

接下来,使用以下命令为应用程序创建数据库:

  • CREATE DATABASE adonis;

    创建数据库adonis ;

You will see the following output:

您将看到以下输出:


   
Output
Query OK, 1 row affected (0.03 sec)

You’ve now successfully created the database for this application.

现在,您已经成功为此应用程序创建了数据库。

Now, enable access to the created database for the new MySQL user. Run the following command to grant all privileges to the user in the database:

现在,为新MySQL用户启用对创建的数据库的访问。 运行以下命令向数据库中的用户授予所有特权:

  • GRANT ALL PRIVILEGES ON adonis.* TO 'sammy'@'localhost';

    将所有特权授予adonis。*至' sammy '@'localhost';

Reload the grant tables by running the following command to apply the changes that you just made:

通过运行以下命令以应用刚刚进行的更改来重新加载授权表:

  • FLUSH PRIVILEGES;

    冲洗特权;

You will see the following output:

您将看到以下输出:


   
Output
Query OK, 0 rows affected (0.00 sec)

Exit the MySQL client with:

使用以下命令退出MySQL客户端:

  • quit;

    退出;

You’ve successfully installed the AdonisJs CLI, created a new AdonisJs project, and installed mysql via npm. You also created the database for this application and set up a MySQL user with the appropriate privileges to it. This is the basic setup for your application and in the next section you will begin to create the necessary views for your application.

您已经成功安装了AdonisJs CLI,创建了一个新的AdonisJs项目,并通过npm安装了mysql 。 您还为此应用程序创建了数据库,并为其设置了具有相应特权MySQL用户。 这是应用程序的基本设置,在下一部分中,您将开始为应用程序创建必要的视图。

第2步-使用边缘模板引擎 (Step 2 — Using the Edge Templating Engine)

AdonisJs is shipped with its own template engine called Edge. It allows you to create a reusable HTML template and enables the introduction of front-end logic into your application with minimal code. Edge provides JavaScript developers with the tools while developing an application to build a component-based layout, write conditionals, use iterations, and create view layers to hold logic. All template files end with the .edge extension and are stored in the resources/views directory.

AdonisJs附带了自己的名为Edge的模板引擎。 它允许您创建可重用HTML模板,并以最少的代码将前端逻辑引入到您的应用程序中。 Edge在开发应用程序时为JavaScript开发人员提供工具,以构建基于组件的布局,编写条件,使用迭代以及创建视图层来保存逻辑。 所有模板文件.edge扩展名结尾,并存储在resources/views目录中。

The following are the views that your application will need to function properly:

以下是您的应用程序正常运行所需的视图:

  • Master Layout: With Edge, you can create a page that will contain the CSS, common JavaScript files, jQuery, and common parts of the user interface that will stay the same throughout the application—for example, the navigation bar, logo, header, etc. Once you’ve established the Master Layout page, other views (pages) in your application will inherit it.

    主版面 :使用Edge,您可以创建一个页面,其中包含CSS,通用JavaScript文件,jQuery和用户界面的通用部分,这些部分在整个应用程序中都将保持不变,例如导航栏,徽标,标题,建立主版面页面后,应用程序中的其他视图(页面)将继承该页面。

  • Index view: This page will use the master layout to inherit common files and will also render contents for the homepage of the application.

    索引视图 :此页面将使用主布局继承通用文件,还将呈现应用程序主页的内容。

  • Login page: This page will also use the master layout and render the form with the input fields for both username and password for users to log in.

    登录页面 :此页面还将使用主布局,并使用用户名和密码的输入字段来呈现表单,以供用户登录。

  • Register page: Here, users will see a form to register and have their details persisted into the database.

    注册页面 :在这里,用户将看到一个表单进行注册,并将其详细信息保存到数据库中。

  • Create quote page: Users will use this page to create an inspirational quote.

    创建报价页面 :用户将使用此页面创建鼓舞人心的报价。

  • Edit quote page: Users will use this page to edit a quote.

    编辑报价页面 :用户将使用此页面来编辑报价。

  • View quote page: Users will use this page to view a particular quote.

    查看报价页面 :用户将使用此页面查看特定报价。

To begin, use the adonis command to create the master layout page by running the following command:

首先,使用adonis命令通过运行以下命令来创建主版面页面:

  • adonis make:view layouts/master

    阿多尼斯(Adonis)Make:查看布局/母版

You’ll see output similar to the following:

您将看到类似于以下内容的输出:


   
Output
✔ create resources/views/layouts/master.edge

This command will automatically create a master.edge file in your resources/views/layouts folder. Open the new file:

此命令将在您的resources/views/layouts文件夹中自动创建一个master.edge文件。 打开新文件:

  • nano resources/views/layouts/master.edge

    纳米资源/视图/布局/master.edge

Add the following code in it:

在其中添加以下代码:

/resources/views/layouts/master.edge
/resources/views/layouts/master.edge
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>adonis-quotes-app</title>
    {{ style('https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css') }}
    {{ style('style') }}
    {{ script('https://code.jquery.com/jquery-3.3.1.slim.min.js') }}
</head>
<body>
    <div class="container-fliud">
        @include('navbar')
        @!section('content')
    </div>
    {{ script('https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js') }}

</body>
</html>

In this file, you include the CDN files for Bootstrap CSS, Bootstrap JavaScript, and jQuery. You add a global CSS file name of style.css and within the div you include a partial file named navbar. To reuse fragments of HTML code that you require across multiple pages in your application, like nav or footer, you can incorporate partials. These are smaller files containing the repeated code making it quicker to update code for these elements in one place rather than at every instance it occurs. The navbar contains markup for a Login and Register buttons, a logo, and a home link.

在此文件中,您包括Bootstrap CSS,Bootstrap JavaScript和jQuery的CDN文件。 您添加一个名为style.css的全局CSS文件,并在div包含一个名为navbar部分文件。 要在应用程序的多个页面中重复使用所需HTML代码片段,例如navfooter ,可以合并部分代码。 这些文件较小,包含重复的代码,因此可以更快地在一个位置而不是在每种情况下更新这些元素的代码。 navbar包含用于“ 登录”和“ 注册”按钮的标记,徽标和主页链接。

With this in place, all the subsequent pages that will be created for this application can extend the master layout and have the navbar rendered without the need to write the content all over again. You’ll create this navbar file later in the tutorial.

有了这个功能,将为该应用程序创建的所有后续页面都可以扩展主版面并显示navbar而无需再次编写内容。 您将在本教程的后面部分创建此navbar文件。

Finally, you define a section tag @!section() to include content from other pages and have them rendered by the master layout. For this to work as expected, all the new pages that will extend the master layout must also define a section tag with the same name (i.e., @section('content')).

最后,您定义一个区域标签@!section()来包含其他页面的内容,并使它们由主版式呈现。 为了使此操作按预期工作,将扩展主版面的所有新页面还必须定义一个具有相同名称的section标签(即@section( ' content ' ) )。

Save and exit the file once you’re finished editing it.

完成编辑后,保存并退出文件。

Next, you will use the adonis command to create the navigation bar:

接下来,您将使用adonis命令创建导航栏:

  • adonis make:view navbar

    阿多尼斯make:view navbar

You’ll see output similar to:

您将看到类似于以下内容的输出:


   
Output
✔ create resources/views/navbar.edge

Open the newly created file:

打开新创建的文件:

  • nano resources/views/navbar.edge

    纳米资源/视图/ navbar.edge

Then add the following code to it:

然后向其中添加以下代码:

/resources/views/navbar.edge
/resources/views/navbar.edge
<nav class="navbar navbar-expand-lg navbar-dark text-white">
    <a class="navbar-brand" >LOGO</a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
    </button>

    <div class="collapse navbar-collapse" id="navbarNav">
        <ul class="navbar-nav">
            <li class="nav-item active ">
                <a class="btn text-white" href="/">Home</a>
            </li>
        </ul>
    </div>
    <div class="navbar-right" id="navbarNav">
        @loggedIn
            <ul class="navbar-nav">
                    <li>
                        <div class="text-right">
                             <a href="{{route('create.quote')}}" class="btn btn-outline-primary">Create Quote</a>
                        </div>
                    </li>

                <li class="nav-item dropdown">
                    <a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                       {{ auth.user.username}}
                    </a>
                    <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
                        <form method="POST" action="{{route('logout')}}">
                            {{ csrfField() }}
                              <button  type="submit" class="dropdown-item" href="">logout</button>
                        </form>
                    </div>
                </li>
            </ul>
        @else
            <ul class="navbar-nav">
                <li class="nav-item active pr-2">
                    <a href="{{route('login.create')}}" class="btn btn-outline-danger">
                      login
                    </a>
                </li>
                <li class="nav-item active pr-2">
                    <a href="{{route('register.create')}}" class="btn btn-outline-primary">
                        Register
                    </a>
                </li>
            </ul>
        @endloggedIn
    </div>
</nav>

In addition to defining the links to the homepage and a button to register and login, you add a @loggedIn tag. With this in place you can write a conditional statement around the authenticated user and display appropriate contents where necessary. For an authenticated user, the application will display their username and a button to create a new quote. If a user is not logged in, your application will display a button to either log in or register. This page will be included as a partial on every page as it was earlier in the master layout for this application.

除了定义指向首页的链接和用于注册和登录的按钮之外,还添加了@loggedIn标记。 使用此功能,您可以在经过身份验证的用户周围编写条件语句,并在必要时显示适当的内容。 对于经过身份验证的用户,应用程序将显示其用户名和一个用于创建新报价的按钮。 如果用户未登录,则您的应用程序将显示一个用于登录或注册的按钮。 此页面将像以前在此应用程序的主布局中一样,部分包含在每个页面中。

Save and exit the file.

保存并退出文件。

Now, you’ll create the index page that you’ll use for the application’s homepage. It will render and display the list of all inspirational quotes that users write:

现在,您将创建用于应用程序主页的索引页面。 它将呈现并显示用户编写的所有励志名言的列表:

  • adonis make:view index

    阿多尼斯make:view index

You will see an output similar to the following:

您将看到类似于以下内容的输出:


   
Output
✔ create resources/views/index.edge

The file created here will be located in resources/views/index.edge. Open the file:

此处创建的文件将位于resources/views/index.edge 。 打开文件:

  • nano resources/views/index.edge

    纳米资源/视图/ index.edge

Then add the following code:

然后添加以下代码:

/resources/views/index.edge
/resources/views/index.edge
@layout('layouts/master')
@section('content')

<div class="container">
    <div class="text-center">
        @if(flashMessage('successmessage'))
            <span class="alert alert-success p-1">{{ flashMessage('successmessage') }}</span>
        @endif
    </div>
    <div class="row">
        @each(quote in quotes)
            <div class="col-md-4 mb-4 quote-wrapper">
                <a href="/view-quote/{{quote.id}}" class="w-100">
                    <div class="card shadow-lg bg-dark text-white">
                        <div class="card-body">
                            <blockquote class="blockquote mb-0">
                                <p>{{quote.body}}</p>
                                <footer class="blockquote-footer">
                                    <cite title="Source Title"> {{quote.username}}</cite>
                                </footer>
                            </blockquote>
                            @if(auth.user.id == quote.user_id)
                              <div>
                                <a  href="/edit-quote/{{quote.id}}" class="btn btn-primary">edit</a>
                                <a href="/delete-quote/{{quote.id}}" class="btn btn-danger">delete</a>
                              </div>
                            @endif
                        </div>
                    </div>
                </a>
            </div>
        @else
         <div class="col-md-12 empty-quote text-center">
                <p>No inspirational quote has been created</p>
         </div>
        @endeach
    </div>
</div>
@endsection

Here, you indicate that this view will use the master layout by extending it. This page can now have access to all the libraries, stylesheets, and the navbar included in the master layout. Next, you iterate over an array of quotes using the built-in @each tag. The quotes array will be passed to this view from the QuoteController that you’ll create later in this tutorial. If there are no quotes, an appropriate message will be displayed.

在这里,您表示此视图将通过扩展使用master布局。 现在,该页面可以访问master布局中包括的所有库,样式表和navbar 。 接下来,使用内置的@each标记遍历一系列quotesquotes数组将从您稍后将在本教程中创建的QuoteController传递到此视图。 如果没有引号,将显示相应的消息。

Save and exit this file.

保存并退出该文件。

Now, to create the login page, run the following command from the terminal:

现在,要创建登录页面,请从终端运行以下命令:

  • adonis make:view auth/login

    adonis make:查看身份验证/登录

You will see an output similar to:

您将看到类似于以下内容的输出:


   
Output
✔ create resources/views/auth/login.edge

This will automatically create an auth folder within resources/views and also create a login.edge file within it. Open the login.edge file:

这将在resources/views自动创建一个auth文件夹,并在其中创建一个login.edge文件。 打开login.edge文件:

  • nano resources/views/auth/login.edge

    纳米资源/视图/auth/login.edge

Add the following content:

添加以下内容:

/resources/views/auth/login.edge
/resources/views/auth/login.edge
@layout('layouts/master')
@section('content')
  <div class="container">
    <div class="row">
      <div class="col-md-4 shadow bg-white mt-5 rounded offset-md-4">
        <form method="POST" action="{{route('login.store')}}">
          {{ csrfField() }}
            <div>
              @if(flashMessage('successmessage'))
                <span class="alert alert-success p-1">{{ flashMessage('successmessage') }}</span>
              @endif
            </div>
            <div class="form-group">
              <label for="email">Email address</label>
              <input type="email" class="form-control" id="email" name="email" value="{{old('email','')}}"  placeholder="Enter email">
              {{ elIf('<span class=text-danger>$self</span>', getErrorFor('email'), hasErrorFor('email')) }}
            </div>
            <div class="form-group">
              <label for="pasword">Password</label>
              <input type="password" class="form-control" id="password" name="password" value="{{old('password','')}}" placeholder="Password">
              {{ elIf('<span class=text-danger>$self</span>', getErrorFor('password'), hasErrorFor('password')) }}
            </div>

            <div class="text-center">
              <button type="submit" class="btn btn-primary">Submit</button>
            </div>
        </form>
      </div>
    </div>
  </div>
@endsection

This file holds a form that contains input elements that you’ll use to collect the username and password of a registered user before they can successfully get authenticated and start creating quotes. Another important element to note on this page is the {{ csrfField() }}. It is a global variable that AdonisJs will use to pass the CSRF access token when sending a POST, PUT, and DELETE request from your application.

该文件包含一个表单,其中包含输入元素,您可以使用它们来收集注册用户的用户名和密码,然后才能成功进行身份验证并开始创建引号。 在此页面上要注意的另一个重要元素是{{ csrfField() }} 。 这是一个全局变量,当您的应用程序发送POSTPUTDELETE请求时,AdonisJs将使用该全局变量来传递CSRF访问令牌。

This was put in place to protect your application from Cross-Site Request Forgery (CSRF) attacks. It works by generating a unique CSRF secret for each user visiting your website and once your users send an HTTP request from the frontend, a corresponding token is generated for this secret and passed along with the request. This will allow the middleware created for this request within AdonisJs to verify that both the token and CSRF secret is valid and belong to the currently authenticated user.

这样做是为了保护您的应用程序免受跨站点请求伪造(CSRF)攻击。 它的工作原理是为每个访问您的网站的用户生成一个唯一的CSRF机密,并且一旦您的用户从前端发送HTTP请求,就会为该机密生成一个相应的令牌并将其与请求一起传递。 这将允许在AdonisJs中为此请求创建的中间件验证令牌和CSRF机密均有效并且属于当前已认证的用户。

Save and exit the file once you’re finished.

完成后,保存并退出文件。

Next, you will create the register page with this command:

接下来,您将使用以下命令创建注册页面:

  • adonis make:view auth/register

    adonis make:查看身份验证/注册

You will see output similar to this:

您将看到类似于以下的输出:


   
Output
✔ create resources/views/auth/register.edge

Locate and open the newly created file in resources/views/auth/register.edge:

resources/views/auth/register.edge找到并打开新创建的文件:

  • nano resources/views/auth/register.edge

    纳米资源/视图/身份验证/register.edge

Add the following code:

添加以下代码:

resources/views/auth/register.edge
资源/视图/身份验证/register.edge
@layout('layouts/master')
@section('content')
  <div class="container ">
    <div class="row">
        <div class="col-md-4  bg-white p-3 mt-5 shadow no-border rounded offset-md-4">
          <form method="POST" action="{{route('register.store')}}">
            {{ csrfField() }}
              <div class="form-group">
                <label for="name">Fullname</label>
                <input type="text" class="form-control" id="name" name="name"  value="{{old('name','')}}" placeholder="Enter Fullname">
                {{ elIf('<span class=text-danger>$self</span>', getErrorFor('name'), hasErrorFor('name')) }}
              </div>
              <div class="form-group">
                <label for="email">Email address</label>
                <input type="email" class="form-control" id="email"  name="email" value="{{old('email','')}}" placeholder="Enter email">
                {{ elIf('<span class=text-danger>$self</span>', getErrorFor('email'), hasErrorFor('email')) }}
              </div>
              <div class="form-group">
                <label for="pasword">Password</label>
                <input type="password" class="form-control" id="password" name="password" placeholder="Password">
                {{ elIf('<span class=text-danger>$self</span>', getErrorFor('password'), hasErrorFor('password')) }}
              </div>
              <div class="text-center">
                  <button type="submit" class="btn btn-primary">Submit</button>
              </div>
          </form>
        </div>
    </div>
  </div>
@endsection

Similarly to what you have on the login page, this file contains an HTML form with input fields to collect the name, email, and password of a user during the registration process. Also included is the {{ csrfField() }} as it is required for each post request for an AdonisJs application.

与登录页面上的内容类似,此文件包含一个HTML表单,该表单带有输入字段,用于在注册过程中收集用户的nameemailpassword 。 还包括{{ csrfField() }}因为对AdonisJs应用程序的每个发布请求都需要它。

Save and exit the file.

保存并退出文件。

Now, you will generate a new file to create an inspirational quote by running the following command from the terminal:

现在,您将通过从终端运行以下命令来生成一个新文件来创建鼓舞人心的报价:

  • adonis make:view quotes/create-quote

    阿多尼斯make:view quotes / create-quote

You will see output like:

您将看到如下输出:


   
Output
✔ create resources/views/quotes/create-quote.edge

Open resources/views/quotes/create-quote.edge:

打开resources/views/quotes/create-quote.edge

  • nano resources/views/quotes/create-quote.edge

    纳米资源/视图/报价/创建quote.edge

And add the following content to it:

并添加以下内容:

/resources/views/quotes/create-quote.edge
/resources/views/quotes/create-quote.edge
@layout('layouts/master')
@section('content')
<div class="container">
    <div class="row">
        <div class="col-md-3"></div>
        <div class="col-md-6 shadow bg-white mt-5 rounded p-3">
            <div class="float-right">
                <a href="/" class="btn btn-outline-dark ">back</a>
            </div>
                <br>

            <div class="clear-fix"></div>
                <form method="POST" action="{{route('store.quote')}}">
                    {{ csrfField() }}
                    <div class="form-group">
                        <label for="quote">Create Quote</label>
                        <textarea type="text" rows="5"  name='body' id="body" class="form-control" id="quote" placeholder="Write an inspirational quote"></textarea>
                    </div>

                    <div class="text-center">
                        <button type="submit" class="btn btn-primary">Submit</button>
                    </div>
                </form>
            </div>
        </div>
        <div class="col-md-3"></div>
    </div>
</div>
@endsection

This page extends the master layout and contains an HTML form with a text area element that allows a user to input text over multiple rows before being posted and handled by the appropriate route.

该页面扩展了主版面,并包含带有文本区域元素HTML表单,该元素使用户可以在通过适当的路线发布和处理之前,在多行中输入文本。

Save and exit the file once you’re finished.

完成后,保存并退出文件。

Next, you will create a page for editing a particular quote. Run the following command from the terminal:

接下来,您将创建一个页面,用于编辑特定报价。 从终端运行以下命令:

  • adonis make:view quotes/edit-quote

    阿多尼斯make:view quotes / edit-quote

You will see the following output:

您将看到以下输出:


   
Output
✔ create resources/views/quotes/edit-quote.edge

Open the file with:

使用以下命令打开文件:

  • nano resources/views/quotes/edit-quote.edge

    纳米资源/视图/报价/编辑quote.edge

Add the following content to resources/views/quotes/edit-quote:

将以下内容添加到resources/views/quotes/edit-quote

/resources/views/quotes/edit-quote.edge
/resources/views/quotes/edit-quote.edge
@layout('layouts/master')
@section('content')
<div class="container">
    <div class="row">
        <div class="col-md-6 shadow bg-white rounded p-3 offset-md-3">
            <div class="float-right">
                <a href="/" class="btn btn-outline-dark ">back</a>
            </div>
            <br>

            <div class="clear-fix"></div>
            <form method="POST" action="/update-quote/{{quote.id}}">
                {{ csrfField() }}
                <div class="form-group">
                    <label for="pasword">Edit Quote</label>
                    <textarea type="text" rows="5"  name='body' id="body" class="form-control" id="quote" placeholder="write the inspirational quote">{{quote.body}}</textarea>
                </div>
                <div class="text-center">
                    <button type="submit" class="btn btn-primary">Update</button>
                </div>

            </form>
        </div>
    </div>
</div>
@endsection

This page holds similar content as the create-quote.edge file—the difference is that it contains the details of a particular quote that needs to be edited, <form method="POST" action="/update-quote/{{quote.id}}">.

此页面包含与create-quote.edge文件类似的内容-区别在于它包含需要编辑的特定报价的详细信息, <form method="POST" action="/update-quote/{{quote.id}}">

Save and exit the file.

保存并退出文件。

Finally, generate a page to view a single inspirational quote:

最后,生成一个页面以查看单个励志名言:

  • adonis make:view quotes/quote

    阿多尼斯make:view quotes / quote

You will see an output similar to this:

您将看到类似于以下的输出:


   
Output
✔ create resources/views/quotes/quote.edge

Open the file with:

使用以下命令打开文件:

  • nano resources/views/quotes/quote.edge

    纳米资源/视图/报价/quote.edge

Add the following code:

添加以下代码:

/resources/views/quotes/quote.edge
/resources/views/quotes/quote.edge
@layout('layouts/master')
@section('content')
<div class="container">
    <div class="row">
        <div class="col-md-6 offset-md-3">
            <div class="card shadow-lg bg-dark text-white">
                <div class="card-body">
                    <div class="float-right">
                        <a href="/" class="btn btn-outline-primary ">back</a>
                    </div>
                        <br>
                    <div class="clear-fix"></div>
                    <blockquote class="blockquote mb-0">
                        <p>{{quote.body}}</p>
                        <footer class="blockquote-footer">
                            <cite title="Source Title">{{quote.username}}</cite>
                        </footer>
                    </blockquote>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

This page renders the details of a particular quote, that includes the body of the quote, quote.body, and the author who created it, quote.username.

此页面呈现特定报价的详细信息,其中包括报价的主体quote.body以及创建报价的作者quote.username

Once you’re finished with the file, save and exit.

完成文件操作后,保存并退出。

You have created all the required pages for your application by using the Edge templating engine. Next, you’ll configure and create a connection to your application’s database.

您已经使用Edge模板引擎为应用程序创建了所有必需的页面。 接下来,您将配置并创建与应用程序数据库的连接。

第3步-创建数据库架构 (Step 3 — Creating a Database Schema)

If you serve your application now it will throw an error as you are yet to connect the application to a database. In this section, you will set up a connection to the database and then use the adonis command to generate a migration file that will be used to create the tables for it.

如果您现在为应用程序提供服务,由于尚未将应用程序连接到数据库,它将引发错误。 在本节中,您将建立与数据库的连接,然后使用adonis命令生成一个迁移文件,该文件将用于为其创建表。

AdonisJs ships with an ORM named Lucid ORM, which provides active record implementation for working with your database. It takes away the hassle of writing SQL queries that retrieve data from the database in realtime. This is especially helpful when working on a complex application that requires a lot of queries. As an example, retrieving all the quotes from your application can be achieved by writing this:

AdonisJs附带一个名为Lucid ORM的ORM ,该ORM提供了用于处理数据库的活动记录实现。 它消除了编写SQL查询以从数据库实时检索数据的麻烦。 在需要大量查询的复杂应用程序上工作时,这特别有用。 例如,通过编写以下代码可以从应用程序中检索所有引号:

const quotes = await Quote.all()

To proceed with the appropriate configuration for your application database, ensure that you are still within the root directory of your application and create a .env file:

要对应用程序数据库进行适当的配置,请确保您仍位于应用程序的根目录中并创建一个.env文件:

  • nano .env

    纳米.env

Open the newly created file and add the following content:

打开新创建的文件并添加以下内容:

.env
.env
HOST=127.0.0.1
PORT=3333
NODE_ENV=development
APP_URL=http://${HOST}:${PORT}
CACHE_VIEWS=false
APP_KEY=bTVOEgUvmTCfkvgrK8gEBC3Qxt1xSYr0
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_USER=sammy
DB_PASSWORD=password
DB_DATABASE=adonis
SESSION_DRIVER=cookie
HASH_DRIVER=bcrypt

By default the database connection for an AdonisJs application is SQLite, which you will update to MySQL here. You also specify the PORT for the application, the application environment, and your database credentials. Ensure that you replace the DB_USER, DB_PASSWORD, and DB_DATABASE placeholder with your credentials.

默认情况下,AdonisJs应用程序的数据库连接为SQLite,您将在此处将其更新为MySQL。 您还可以为应用程序,应用程序环境和数据库凭据指定PORT 。 确保使用您的凭据替换DB_USERDB_PASSWORDDB_DATABASE占位符。

Next, you will create the model and a migration file for Quote using the Adonis CLI. To accomplish that, run the following command:

接下来,您将使用Adonis CLI为Quote创建模型和迁移文件。 为此,请运行以下命令:

  • adonis make:model Quote --migration

    adonis make:model Quote --migration

You’ll see output similar to the following:

您将看到类似于以下内容的输出:


   
Output
✔ create app/Models/Quote.js ✔ create database/migrations/1568209992854_quote_schema.js

This command will create a model for Quote in the app/Models folder and a schema file in the database/migrations folder. The newly created schema file will be prefixed with the current timestamp. Open the schema file with:

此命令将在app/Models文件夹中创建Quote app/Models并在database/migrations文件夹中创建架构文件。 新创建的架构文件将以当前时间戳作为前缀。 使用以下命令打开模式文件:

  • nano database/migrations/1568209992854_quote_schema.js

    纳米数据库/迁移/1568209992854_quote_schema.js

Update its content with the following code:

使用以下代码更新其内容:

database/migrations/…quote_schema.js
数据库/迁移/…quote_schema.js
'use strict'
/** @type {import('@adonisjs/lucid/src/Schema')} */
const Schema = use('Schema')
class QuoteSchema extends Schema {
  up () {
    this.create('quotes', (table) => {
      table.increments()
      table.integer('user_id').notNullable()
      table.string('username', 80).notNullable()
      table.string('body').notNullable()
      table.timestamps()
    })
  }
  down () {
    this.drop('quotes')
  }
}
module.exports = QuoteSchema

A schema file in AdonisJs requires two different methods, which are:

AdonisJs中的模式文件需要两种不同的方法,分别是:

  • up: Used to create a new table or alter an existing one.

    up :用于创建新表或更改现有表。

  • down: Used to revert the changes applied in the up method.

    down :用于还原在up方法中应用的更改。

In addition to the timestamps() and increments() fields, you update the content of the schema file with the field attributes user_id, username, and the body of a quote that will be created. The user_id and username fields reference the details of the user who create a particular quote. This defines a one to many relationship and means a user can own an infinite number of quotes while a single quote can only belong to a user.

除了timestamps()increments()字段之外,您还使用字段属性user_idusername和将要创建的报价body来更新模式文件的内容。 user_idusername字段引用创建特定报价的用户的详细信息。 这定义了一对多关系 ,意味着用户可以拥有无​​限数量的报价,而单个报价只能属于用户。

Save and exit the file.

保存并退出文件。

AdonisJs comes installed with a User model and its migration file by default, which requires only a small modification to establish the relationship between the User and Quote model.

默认情况下,AdonisJs随User模型及其迁移文件一起安装,只需稍作修改即可建立User模型与Quote模型之间的关系。

Open the User model in app/Models/User.js:

app/Models/User.js打开User模型:

  • app/Models/User.js

    app / Models / User.js

Add this method immediately after the tokens() method:

tokens()方法之后立即添加此方法:

app/Models/User.js
app / Models / User.js
...
class User extends Model {
  ...
  tokens () {
    return this.hasMany('App/Models/Token')
  }

  quote () {
    return this.hasMany('App/Models/Quote')
  }
}

module.exports = User

This will establish a one to many relationship with the Quote table using user_id as the foreign key.

这将使用user_id作为外键与Quote表建立一对多关系。

Save and exit the file.

保存并退出文件。

To wrap up this section, use the following command to run migrations, which will execute the up() method of all migration files:

要结束本节,请使用以下命令来运行迁移,该命令将执行所有迁移文件的up()方法:

  • adonis migration:run

    阿多尼斯迁移:运行

You will see output similar to the following:

您将看到类似于以下内容的输出:


   
Output
migrate: 1503248427885_user.js migrate: 1503248427886_token.js migrate: 1568209992854_quote_schema.js Database migrated successfully in 3.42 s

You’ve configured and secured a connection with your database. You also created a Quote model and its corresponding schema file and created a one to many relationship between a User and Quote. Next, you’ll generate the routes and create controllers to handle HTTP requests and the business logic to create, edit, and delete an inspirational quote.

您已经配置并保护了与数据库的连接。 您还创建了Quote模型及其相应的架构文件,并在UserQuote之间创建了一对多关系。 接下来,您将生成路由并创建控制器以处理HTTP请求,并创建业务逻辑以创建,编辑和删除鼓舞人心的报价。

第4步-创建控制器并设置路由 (Step 4 — Creating Controllers and Setting Up Routes)

In this section, you will start by creating controllers to handle all the logic for the application and later attach these controllers to a specific route for it to be accessed by users via a URL.

在本部分中,您将首先创建控制器来处理应用程序的所有逻辑,然后将这些控制器附加到特定的路由,以便用户通过URL访问它。

To start, you’ll use the Adonis CLI to create a new HTTP request controller to handle all authentication processes for your application by running the following command:

首先,您将使用Adonis CLI创建一个新的HTTP请求控制器,以通过运行以下命令来处理应用程序的所有身份验证过程:

  • adonis make:controller Auth --type http

    adonis make:controller Auth --type http

This command will create an AuthController.js file and save it within app/Controllers/Http folder. You use the flag --type to indicate that you want this controller to be an HTTP controller.

此命令将创建一个AuthController.js文件,并将其保存在app/Controllers/Http文件夹中。 您使用标志--type表示您希望此控制器为HTTP控制器。

You will see an output similar to the following:

您将看到类似于以下内容的输出:


   
Output
✔ create app/Controllers/Http/AuthController.js

Next, open the newly created controller file:

接下来,打开新创建的控制器文件:

  • nano app/Controllers/Http/AuthController.js

    纳米应用程序/控制器/ Http / AuthController.js

Update it with the following content:

用以下内容更新它:

app/Controllers/Http/AuthController.js
app / Controllers / Http / AuthController.js
'use strict'
const User = use('App/Models/User')
class AuthController {

    loginView({ view }) {
        return view.render('auth.login')
    }
    registrationView({ view }) {
        return view.render('auth.register')
    }

    async postLogin({ request, auth, response}) {
        await auth.attempt(request.input('email'), request.input('password'))
        return response.route('index')
    }

    async postRegister({ request, session, response }) {
        const user = await User.create({
            username: request.input('name'),
            email: request.input('email'),
            password: request.input('password')
        })
        session.flash({ successmessage: 'User have been created successfully'})
        return response.route('login.create');
    }

    async logout ({ auth, response }) {
        await auth.logout()
        return response.route('/')
    }
}
module.exports = AuthController

In this file, you import the User model and then create two methods named loginView() and registerView() to render the login and register pages respectively. Finally, you create the following asynchronous methods:

在此文件中,导入User模型,然后创建两个名为loginView()registerView()方法分别渲染登录页面和注册页面。 最后,创建以下异步方法:

  • postLogin(): This method will obtain the value of the email and password posted through the help of the inbuilt request method in AdonisJs and then validate this user against the details in the database. If such a user exists in the database and has inputted the correct credential, they will be redirected back to the homepage and authenticated before they can create a new quote. Otherwise, a message indicating the wrong credentials will be displayed.

    postLogin() :此方法将通过AdonisJs中内置request方法的帮助获取张贴的emailpassword的值,然后根据数据库中的详细信息验证此用户。 如果这样的用户存在于数据库中并输入了正确的凭据,则他们将被重定向回首页并进行身份验证,然后才能创建新报价。 否则,将显示一条指示错误凭证的消息。

  • postRegister(): This will receive the value of the username, email, and password for a user to create an account for such user in the database. A message indicating that such user has been created successfully will be passed to the session and the user will be redirected to the login page to get authenticated and start creating a quote.

    postRegister() :这将接收usernameemailpassword的值,以供用户在数据库中为此用户创建帐户。 指示该用户已成功创建的消息将传递到会话,并且该用户将被重定向到登录页面以进行身份​​验证并开始创建报价。

  • logout(): This method will handle the logout functionality and redirect the user back to the homepage.

    logout() :此方法将处理注销功能,并将用户重定向回首页。

Save and exit the file.

保存并退出文件。

Now that you have set up the controller to register and authenticate users, you will proceed by creating an HTTP request controller to manage all operations regarding quotes.

现在,您已经设置了用于注册和验证用户的控制器,接下来将创建一个HTTP请求控制器来管理有关报价的所有操作。

Back in the terminal, run the following command to create the QuoteController:

返回终端,运行以下命令来创建QuoteController

  • adonis make:controller Quote --type http --resource

    adonis make:controller Quote --type http --resource

Using the --resource flag will create a controller with predefined resourceful methods to do CRUD (Create, Read, Update, and Delete) operations.

使用--resource标志将创建具有预定义的资源丰富方法的控制器,以执行CRUD(创建,读取,更新和删除)操作。

You will see:

你会看见:


   
Output
✔ create app/Controllers/Http/QuoteController.js

Locate this file within app/Controllers/Http/QuoteController.js:

app/Controllers/Http/QuoteController.js找到此文件:

  • nano app/Controllers/Http/QuoteController.js

    纳米应用程序/控制器/ Http / QuoteController.js

Update it with the following content:

用以下内容更新它:

app/Controllers/Http/QuoteController.js
app / Controllers / Http / QuoteController.js
'use strict'
const Quote = use('App/Models/Quote')

class QuoteController {

  async index ({ view }) {
    const quote = await Quote.all()
    return view.render('index', {
      quotes: quote.toJSON()
    })
  }

  async create ({ view }) {
    return view.render('quotes.create-quote')
  }

  async store ({ request,auth,session, response }) {
    const quote = await Quote.create({
      user_id: auth.user.id,
      username: auth.user.username,
      body: request.input('body')
    })
    session.flash({ 'successmessage': 'Quote has been created'})
    return response.redirect('/')
  }

  async show ({ params, view }) {
    const quote = await Quote.find(params.id)
    return view.render('quotes.view-quote', {
      quote: quote.toJSON()
    })
  }

  async edit ({ params, view }) {
    const quote = await Quote.find(params.id)
    return view.render('quotes.edit-quote', {
      quote: quote.toJSON()
    })
  }

  async update ({ params, request, response, session }) {
    const quote = await Quote.find(params.id)
    quote.body = request.input('body')
    await quote.save()
    session.flash({'successmessage': 'Quote has been updated'})
    return response.redirect('/')
  }

  async destroy ({ params, response, session }) {
    const quote = await Quote.find(params.id)
    await quote.delete()
    session.flash({'successmessage': 'Quote has been deleted'})
    return response.redirect('/')
  }
}
module.exports = QuoteController

In this controller, you imported the Quote model and updated the following methods that were automatically created by using AdonisJs CLI:

在此控制器中,您导入了Quote模型并更新了以下使用AdonisJs CLI自动创建的方法:

  • index(): to fetch all quotes from the database and render it on the homepage of the application.

    index() :从数据库中获取所有引号并将其呈现在应用程序的主页上。

  • create(): to render a page for creating quotes.

    create() :呈现用于创建引号的页面。

  • store(): to persist a newly created quote into the database and return an appropriate response.

    store() :将新创建的报价持久保存到数据库中并返回适当的响应。

  • show(): to obtain the id of a particular quote, retrieve it from the database, and render it on the edit quote page.

    show() :获取特定报价的id ,从数据库中检索它,然后在编辑报价页面上呈现它。

  • edit(): to obtain the detail of a particular quote from the database and render it for editing.

    edit() :从数据库中获取特定报价的详细信息,并将其呈现以进行编辑。

  • update(): to process any update to a quote and redirect the user back to the homepage.

    update() :处理对报价的任何更新,并将用户重定向回首页。

  • destroy(): to delete a particular quote and remove it entirely from the database.

    destroy() :删除特定的报价并将其完全从数据库中删除。

Save and exit the file.

保存并退出文件。

After creating all the necessary controllers for this application, you can now set up the routes so that users can easily interact with your application. To begin, navigate to start/routes.js file

在为该应用程序创建所有必要的控制器之后,您现在可以设置路由,以便用户可以轻松地与您的应用程序进行交互。 首先,导航到start/routes.js文件

  • nano start/routes.js

    纳米启动/routes.js

Replace its content with the following:

将其内容替换为以下内容:

start/routes.js
start / routes.js
'use strict'
const Route = use('Route')

Route.get('/','QuoteController.index').as('index')
Route.get('/register','AuthController.registrationView').as('register.create')
Route.post('/register-store','AuthController.postRegister').as('register.store').validator('Register')
Route.get('/login','AuthController.loginView').as('login.create')
Route.post('/login-store','AuthController.postLogin').as('login.store')
Route.get('/view-quote/:id','QuoteController.show').as('view.quote')

Route.group(() => {
    Route.get('/create-quote','QuoteController.create').as('create.quote')
    Route.post('/store-quote','QuoteController.store').as('store.quote')
    Route.get('/edit-quote/:id','QuoteController.edit').as('edit.quote')
    Route.post('/update-quote/:id','QuoteController.update').as('update.quote')
    Route.get('/delete-quote/:id','QuoteController.destroy').as('delete.quote')
    Route.post('/logout','AuthController.logout').as('logout')
}).middleware(['auth'])

Here, you define the path for each route in your application, specify the HTTP verbs for each action, and bound the route to a particular method in each controller. You also name each of these routes as they have been referenced within the controllers and views.

在这里,您可以为应用程序中的每个路由定义路径,为每个操作指定HTTP动词,并将路由绑定到每个控制器中的特定方法。 您还可以为每个路由命名,因为它们已在控制器和视图中被引用。

To ensure that only authenticated users can access all the quotes routes, you assign a group middleware named to it. And lastly, you attach a validator method to the register.store route to validate user input.

为了确保只有经过身份验证的用户才能访问所有报价路由,您可以为其分配一个名为“组中间件”的中间件。 最后,将验证器方法附加到register.store路由以验证用户输入。

Save and exit the file.

保存并退出文件。

You’ve created your controllers and set up the routes for your application. Next you’ll create the validator method defined in this step.

您已经创建了控制器并为您的应用程序设置了路由。 接下来,您将创建在此步骤中定义的验证器方法。

步骤5 —验证用户输入 (Step 5 — Validating User Input)

AdonisJs does not have validators built-in by default. As a result you’ll install and register the validator for your application manually.

默认情况下,AdonisJs没有内置验证器。 因此,您将手动安装并注册应用程序的验证器。

Run the following command to install it:

运行以下命令进行安装:

  • adonis install @adonisjs/validator

    阿多尼斯安装@ adonisjs / validator

Open the following file to register the validator provider:

打开以下文件以注册验证程序提供程序:

  • nano start/app.js

    纳米启动/ app.js

Then register the validator provider by appending it to the list of providers as shown following:

然后通过将验证器提供程序附加到提供程序列表中来注册它,如下所示:

start/app.js
开始/ app.js
...
const providers = [
   ...
   '@adonisjs/cors/providers/CorsProvider',
   '@adonisjs/shield/providers/ShieldProvider',
   '@adonisjs/session/providers/SessionProvider',
   '@adonisjs/auth/providers/AuthProvider',
   '@adonisjs/validator/providers/ValidatorProvider'
]

Now that you have installed and registered the validator provider within your application, create a custom validator to validate user input during registration with the following command:

现在,您已经在应用程序中安装并注册了验证程序提供程序,现在创建一个自定义验证程序,以在注册过程中使用以下命令验证用户输入:

  • adonis make:validator Register

    adonis make:validator注册

This will create a Register.js file in the App/validators directory. Open the file with:

这将在App/validators目录中创建一个Register.js文件。 使用以下命令打开文件:

  • nano app/Validators/Register.js

    纳米应用程序/验证程序/ Register.js

Add the following code to the file:

将以下代码添加到文件中:

app/Validators/Register.js
app / Validators / Register.js
'use strict'
class Register {
  get rules () {
    return {
      name:'required',
      email:'required|email|unique:users',
      password:'required|min:8'
    }
  }

  get messages(){
    return{
      'name.required':'Full name is required',
      'email.required':'email is required',
      'email.unique':'email already exists',
      'password.required':'password is required',
      'password.min':'password should be at least 8 characters'
    }
  }
}
module.exports = Register

You define rules for specific fields in your application. If validations fail at any time, the validator automatically sets the error as a flash message and the user will be redirected back to the form.

您可以为应用程序中的特定字段定义规则。 如果验证在任何时候失败,验证器会自动将错误设置为Flash消息,并且用户将被重定向回表单。

Save and exit the file once you’re finished editing.

完成编辑后,保存并退出文件。

Finally, to add styling for your application, open the following file:

最后,要为您的应用程序添加样式,请打开以下文件:

  • nano public/style.css

    纳米public / style.css

Replace its contents with the following:

将其内容替换为以下内容:

/public/style.css
/public/style.css
@import url('https://fonts.googleapis.com/css?family=Montserrat:300');

html, body {
  height: 100%;
  width: 100%;
}

body {
  font-family: 'Montserrat', sans-serif;
  font-weight: 300;
  background-image: url("/splash.png");
  background-color: #220052;
}

* {
  margin: 0;
  padding: 0;
}

a {
  color: inherit;
  text-decoration: underline;
}

p {
  margin: 0.83rem 0;
}

.quote-wrapper {
  margin-top: 20px;
}

.quote-wrapper a {
  text-decoration: none;
}

.quote-wrapper a:hover {
  color: #ffffff;
}

.empty-quote {
  color: #ffffff;
}

form {
  padding: 20px;
}

In this file you update the CSS styling of your application in the style.css file.

在此文件中,您可以在style.css文件中更新应用程序CSS样式。

You’ve installed and registered a validator provider for the purpose of checking users’ input during the registration process. You also updated the content of your stylesheet to add more styling to the application. In the final step you’ll test your application.

您已经安装并注册了验证程序提供程序,目的是在注册过程中检查用户的输入。 您还更新了样式表的内容,以向应用程序添加更多样式。 在最后一步,您将测试您的应用程序。

第6步-服务应用程序 (Step 6 — Serving the Application)

In this step, you’ll serve your application and create a user and password to test the authentication. You’ll also add a quote to your app and view this on the homepage.

在此步骤中,您将为应用程序提供服务并创建用户和密码以测试身份验证。 您还将在应用程序中添加报价,并在主页上查看。

To test your application, start the development server with the following command from the root directory of your application:

要测试您的应用程序,请从应用程序的根目录中使用以下命令启动开发服务器:

  • adonis serve --dev

    阿多尼斯服务--dev

This will start the application on the port defined inside the root .env file, which is 3333. Navigate to http://localhost:3333 from your browser.

这将在根.env文件内部定义的端口3333上启动应用程序。 从浏览器导航到http:// localhost:3333 。

The homepage is empty at the moment as you have not created any quotes. Click on the Register button.

由于您尚未创建任何引号,因此该主页目前为空。 单击注册按钮。

Enter your details and click on the Submit button to complete the registration process. You will be redirected to the login page. Enter your email address and password for authentication.

输入您的详细信息,然后单击“ 提交”按钮以完成注册过程。 您将被重定向到登录页面。 输入您的电子邮件地址和密码进行身份验证。

Once you’re authenticated, click on the Create Quote button.

通过身份验证后,单击“ 创建报价”按钮。

Enter a quote and navigate to the View all page to see your quote.

输入报价,然后导航至“ 查看全部”页面以查看报价。

You’ve tested your application by creating and authenticating a user and then writing a quote.

您已经通过创建和验证用户并编写报价来测试您的应用程序。

结论 (Conclusion)

In this tutorial you’ve built a web application with AdonisJs. You set up the application using the AdonisJs CLI and leveraged the CLI for creating other relevant files such as controllers, models, and views.

在本教程中,您已经使用AdonisJs构建了一个Web应用程序。 您可以使用AdonisJs CLI设置应用程序,并利用CLI创建其他相关文件,例如控制器,模型和视图。

You can build web applications with this framework irrespective of their size and complexity. Feel free to download the source code for this project here on GitHub. To explore further features, you can also visit the official documentation.

您可以使用此框架构建Web应用程序,而不管它们的大小和复杂程度。 随意下载源代码,这个项目在这里 GitHub上。 要探索更多功能,您还可以访问官方文档 。

If you would like to explore some of our other JavaScript framework tutorials, check out the following:

如果您想探索其他一些JavaScript框架教程,请查看以下内容:

  • How To Build a Customer List Management App with React and TypeScript

    如何使用React和TypeScript构建客户列表管理应用

  • How To Build a Blog with Nest.js, MongoDB, and Vue.js

    如何使用Nest.js,MongoDB和Vue.js构建博客

  • How To Build a Weather App with Angular, Bootstrap, and the APIXU API

    如何使用Angular,Bootstrap和APIXU API构建Weather App

翻译自: https://www.digitalocean.com/community/tutorials/how-to-build-an-inspirational-quote-application-using-adonisjs-and-mysql

mysql桌面应用程序


http://www.niftyadmin.cn/n/3649500.html

相关文章

推荐一款截图神器——FSCapture

FSCapture FSCapture是一款抓屏工具&#xff0c;体积小巧、功能强大&#xff0c;不但具有常规截图等功能&#xff0c;更有从扫描器获取图像&#xff0c;和将图像转换为 PDF文档等功能。还有图片编辑&#xff0c;屏幕录像&#xff0c;编辑视频等强大的功能。以前博客的图片和视频…

Android Studio项目转为Eclipse开发以后遇到的问题

Android SDK结构不同导致报错 Android Studio和Eclipse不能共用一套Android SDK&#xff0c;因为使用SDK的结构不一样。把Android Studio项目转为eclipse开发&#xff0c;首先在eclipse新建一个Android项目&#xff0c;然后将Java逻辑代码和XML布局文件复制到新项目里面即可。不…

Android工程师必备的网址

实用工具集锦 Android Lifecycle https://github.com/xxv/android-lifecycle Safe.ijiami http://safe.ijiami.cn/ TinyPNG https://tinypng.com/ Android Layout Finder Android Layout Finder Android Asset Studio http://romannurik.github.io/AndroidAssetStudio/ JSON Va…

react无限滚动_如何使用React和CSS Grid构建无限滚动图片库

react无限滚动介绍 (Introduction) In this tutorial, we will use the React frontend Javascript framework and CSS Grid to build an infinite scroll image gallery, using the Unsplash API to embed the photographic images. Using a codepen coding challenge from Sc…

[Domino]Tomcat需要NCSO.jar来定位Domino异常

[Domino]Tomcat需要NCSO.jar来定位Domino异常编写者日期关键词郑昀ultrapower2005-6-15Java Tomcat Axis NotesFactory我试图从Web Service访问Domino。Web Service的构建方法是&#xff1a;AxisTomcat&#xff0c;在Eclipse中加入了tomcatPluginV31beta插件&#xff0c;从而很…

初识Java设计模式

设计模式简介 设计模式(Design pattern)代表了最佳的实践&#xff0c;通常被有经验的面向对象的软件开发人员所采用。设计模式是软件开发人员在软件开发过程中面临的一般问题的解决方案。这些解决方案是众多软件开发人员经过相当长的一段时间的试验和错误总结出来的。设计模式是…

如何在Ubuntu 18.04上使用Ansible获取让我们加密证书

The author selected the Electronic Frontier Foundation to receive a donation as part of the Write for DOnations program. 作者选择了电子前沿基金会来接受捐款&#xff0c;这是Write for DOnations计划的一部分。 介绍 (Introduction) Modern infrastructure manageme…

如何在一个没有root权限的Android设备上创建一个SOCKS代理(英文转载)

How to Setup a SOCKS Proxy for Android Without Root原网址&#xff1a;http://www.devineloper.com/2013/08/28/setup-socks-proxy-android-without-root/ As the number of mobile Internet-connected devices continues to rise, so does the number of public-WiFi acces…