如何使用vue-router设置Vue.js身份验证和路由处理

介绍 (Introduction)

Vue.js is a progressive JavaScript framework for building front-end applications. Coupled with vue-router, we can build high performance applications with complete dynamic routes. Vue-router is an efficient tool and can efficiently handle authentication in our Vue application.

Vue.js是用于构建前端应用程序的渐进式JavaScript框架。 结合vue-router ,我们可以构建具有完整动态路由的高性能应用程序。 Vue路由器是一种高效的工具,可以在我们的Vue应用程序中有效地处理身份验证。

In this tutorial, we will look at using vue-router to handle authentication and access control for different parts of our Vue.js application.

在本教程中,我们将研究如何使用vue-router处理Vue.js应用程序不同部分的身份验证和访问控制。

步骤1 —安装Vue CLI和创建应用程序 (Step 1 — Installing Vue CLI and Creating an Application)

To begin, install the Vue CLI and create a Vue application with it:

首先,安装Vue CLI并使用它创建一个Vue应用程序:

  • npm install -g @vue/cli

    npm install -g @ vue / cli
  • npm install -g @vue/cli-init

    npm install -g @ vue / cli-init
  • vue init webpack vue-router-auth

    vue初始化webpack vue-router-auth

Follow the setup prompt and complete the installation of this application. If you are not sure of an option, click the return key (ENTER key) to continue with the default option. When asked to install vue-router, accept the option, because we need vue-router for this application.

按照安装提示完成此应用程序的安装。 如果不确定选项,请单击返回键( ENTER键)以继续使用默认选项。 当要求安装vue-router时,请接受该选项,因为我们需要此应用程序的vue-router。

第2步-设置Node.js服务器 (Step 2 — Set Up Node.js Server)

Next, we will set up a Node.js server that will handle authentication for us. For our Node.js server, we will use SQLite as the database of choice.

接下来,我们将设置一个Node.js服务器来为我们处理身份验证。 对于我们的Node.js服务器,我们将使用SQLite作为选择的数据库。

Run the following command to install SQLite driver:

运行以下命令以安装SQLite驱动程序:

  • npm install --save sqlite3

    npm install-保存sqlite3

Because we are dealing with passwords, we need a way to hash passwords. We will use bcrypt to hash all our passwords. Run the following command to install it:

因为我们正在处理密码,所以我们需要一种哈希密码的方法。 我们将使用bcrypt哈希所有密码。 运行以下命令进行安装:

  • npm install --save bcrypt

    npm install-保存bcrypt

We also want a way to confirm the users we authenticate when they try to make a request to a secured part of our application. For this, we will use JWT. Run the following command to install the JWT package we will use:

我们还希望有一种方法可以在我们尝试向我们的应用程序的受保护部分提出请求时确认我们进行身份验证的用户。 为此,我们将使用JWT 。 运行以下命令以安装我们将使用的JWT软件包:

  • npm install jsonwebtoken --save

    npm install jsonwebtoken-保存

To read json data, we will send to our server, we need body-parser. Run the following command to install it:

要读取json数据,我们将发送到服务器,我们需要body-parser 。 运行以下命令进行安装:

npm install --save body-parser

Now that it’s all set, let us create a Node.js server that would handle user authentication. Create a new directory named server. This is where we will store everything we will use to make our node backend.

至此,我们创建了一个可以处理用户身份验证的Node.js服务器。 创建一个名为server的新目录。 在这里,我们将存储用于制作节点后端的所有内容。

In the server directory, create a file and save it as app.js. Add the following to it:

在服务器目录中,创建一个文件并将其另存为app.js 向其中添加以下内容:

"use strict";
const express = require('express');
const DB = require('./db');
const config = require('./config');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const bodyParser = require('body-parser');

const db = new DB("sqlitedb")
const app = express();
const router = express.Router();

router.use(bodyParser.urlencoded({ extended: false }));
router.use(bodyParser.json());

We have required all the packages we need for our application, defined the database, and created an Express server and router.

我们需要应用程序所需的所有软件包,定义了数据库,并创建了Express服务器和路由器。

Now, let’s define CORS middleware to ensure we do not run into any cross origin resource errors:

现在,让我们定义CORS中间件,以确保我们不会遇到任何跨源资源错误:

// CORS middleware
const allowCrossDomain = function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', '*');
    res.header('Access-Control-Allow-Headers', '*');
    next();
}

app.use(allowCrossDomain)

Many people would use a CORS package here, but we do not have any complicated configurations, so this is fine.

很多人会在这里使用CORS软件包,但是我们没有任何复杂的配置,所以很好。

Let’s define the route for registering a new user:

让我们定义注册新用户的途径:

router.post('/register', function(req, res) {
    db.insert([
        req.body.name,
        req.body.email,
        bcrypt.hashSync(req.body.password, 8)
    ],
    function (err) {
        if (err) return res.status(500).send("There was a problem registering the user.")
        db.selectByEmail(req.body.email, (err,user) => {
            if (err) return res.status(500).send("There was a problem getting user")
            let token = jwt.sign({ id: user.id }, config.secret, {expiresIn: 86400 // expires in 24 h
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值