从0到1开发测试平台(十一)前端登录页面的编写及与后端登录接口的交互

时间:2022-07-24
本文章向大家介绍从0到1开发测试平台(十一)前端登录页面的编写及与后端登录接口的交互,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

前言

前面的文章已经把后台登录接口准备完毕,接下来就是前端页面的编写以及前后端交互了,这里前后端交互我们用的是axios。axios是通过promise实现对ajax技术的一种封装,就像jQuery实现ajax封装一样。既然底层仍然是ajax通过异步请求与后台交互,就自然会遇到跨域的问题,这篇文章后面也会提及如何解决跨域问题。

解决跨域问题主要是有两个方向

  • 通过修改nginx配置
  • 通过修改继承WebMvcConfigurerAdapter重写 addCorsMappings方法

这里我们选择第二种,接下来就详细描述下前端登录功能的实现.

| 在components目录下新建Login组件

<template>
    <div>
        登录组件
    </div>
</template>

<script>
    export default {

    }
</script>

<style lang="less" scoped>
</style>

| 在router/index.js路由文件里导入Login组件

import Login from '../components/Login.vue'

| 在路由文件router/index.js文件的routes数组里增加登录路由

{
    path: '/login',
    component: Login
  }

| 在app.vue根组件中增加路由占位符

<template>
  <div id="app">
    <router-view></router-view>
  </div>
</template>

| 打开地址http://localhost:8080/#/login便能成功访问到我们增加的Login组件了

| 在router/index.js路由文件的routes数组里 增加默认路由(这样访问地址/就会自动跳转到Login组件)

{
    path: '/',
    redirect: '/login'
  }

| 在cmd窗口使用vue-ui命令,在打开的项目管理页面里面点击依赖安装less-loader和less开发依赖库,安装完成之后需要重启项目

| 在assets目录下新建css目录,然后在css目录新建global.css文件

html,body,#app{
    height: 100%;
    margin: 0;
    padding: 0;
}

| 在main.js文件里导入global.css

import './assets/css/global.css'

| 在plugins/element.js文件里按需导入element ui组件

import Vue from 'vue'
import { Button,Form,FormItem,Input } from 'element-ui'

Vue.use(Button)
Vue.use(Form)
Vue.use(FormItem)
Vue.use(Input)

| 登录页面布局(界面上的el-form,el-button,el-input等组件的用法可以打开element-ui官网查看用法,官网文档地址https://element.eleme.cn/#/zh-CN/component/installation)

 <el-form ref="loginFormRef" label-width="0px" class="login_form">
                <!--用户名-->
                <el-form-item>
                    <el-input prefix-icon="iconfont icon-user"></el-input>
                </el-form-item>
                <!--密码-->
                <el-form-item>
                    <el-input prefix-icon="iconfont icon-3702mima"></el-input>
                </el-form-item>
                <!--按钮区域-->
                <el-form-item class="btns">
                    <el-button type="primary">登录</el-button>
                    <el-button type="info">重置</el-button>
                </el-form-item>
            </el-form>

| 由于密码的Input框是密文所以密码对应的input框要加type="password"属性

<el-input prefix-icon="iconfont icon-3702mima" type="password"></el-input>

| 数据绑定,需要为用户名密码输入框绑定数据

(1)在data添加绑定数据

data(){
            return {
                loginForm:{
                    username: '',
                    password: ''
                }
            };
        }

(2)form表单加上:model="loginForm"绑定loginForm

<el-form :model="loginForm" label-width="0px" class="login_form">

(3)用户名输入框加上v-model="loginForm.username"绑定loginForm.username

<el-input v-model="loginForm.username" prefix-icon="iconfont icon-user"></el-input>

(4)密码输入框加上v-model="loginForm.password"绑定loginForm.password

<el-input v-model="loginForm.password" prefix-icon="iconfont icon-3702mima" type="password"></el-input>

| 添加表单验证

(1)data里添加表单验证规则

data(){
            return {
                loginForm:{
                    username: '',
                    password: ''
                },
                loginFormRules:{
                    username: [
                        { required: true, message: '请输入登录名称', trigger: 'blur' },
                        { min: 3, max: 11, message: '长度在 3 到 11 个字符', trigger: 'blur' }
                    ],
                    password: [
                        { required: true, message: '请输入登录密码', trigger: 'blur' },
                        { min: 6, max: 15, message: '长度在 6 到 16 个字符', trigger: 'blur' }
                    ]
                }
            };
        },

(2)form添加:rules="loginFormRules"关联验证规则

<el-form ref="loginFormRef" :model="loginForm" :rules="loginFormRules" label-width="0px" class="login_form">

(3)用户名input框通过el-form-item添加prop="username"来关联username验证规则

<el-form-item prop="username">

(4)密码input框通过el-form-item添加prop="password"来关联password验证规则

<el-form-item prop="password">

| 通过el-form添加ref="loginFormRef"并且通过this.$refs来获取当前表单对象

| 重置表单数据

(1)在methods添加resetLoginForm方法

(2)通过表单的resetFields方法来重置表单数据(包括表单验证结果)

methods:{
            resetLoginForm(){
                this.$refs.loginFormRef.resetFields();
            }
        }

(3)为重置按钮绑定resetLoginForm

<el-button type="info" @click="resetLoginForm">重置</el-button>

| 登录组件的预验证

(1)在methods里面添加login方法

(2)调用表单的validate方法来预验证表单数据

login(){
                this.$refs.loginFormRef.validate((valid)=>{
                    if (!valid) return;
                });
            }

(3)为登录按钮绑定login方法

<el-button type="primary" @click="login">登录</el-button>

| 请求后端login接口

(1).在main.js文件里导入axios

import axios from 'axios'
Vue.prototype.$http = axios

(2).在main.js里设置请求根路径

axios.defaults.baseURL = 'http://127.0.0.1:8082/api/v1/'

(3)在Login组件的login方法里发起网络请求调用后台登录接口

const{data:res} = await this.$http.post("login",this.loginForm);

| 配置弹窗提示,在element.js文件中导入element ui的Message组件然后在组件里就可以通过this.$message调用弹窗方法弹出提示框

import { Button,Form,FormItem,Input,Message} from 'element-ui'

Vue.prototype.$message = Message

经过以上配置我们点击登录按钮,结果发现前端接口报错了

是不是一脸懵逼,403是个什么鬼,我们点开console终于发现了问题所在

提示跨域访问不被允许,接下来我们配置跨域访问

| 配置跨域访问

我们需要在后端增加跨域允许配置

package com.mingdeng.community.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class CorsConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowCredentials(true)
                .allowedMethods("GET", "POST", "DELETE", "PUT")
                .maxAge(3600);
    }
}

配置好跨域允许之后,我们再次点击登录按钮,看到后端接口调用成功并返回用户信息

| 完善login方法

login(){
                this.$refs.loginFormRef.validate(async valid=>{
                    // this.$message.success("登录成功")
                    if (!valid) return;
                    const{data:res} = await this.$http.post("user/login",this.loginForm);
                    if (!res.success) return  this.$message.error(res.message);
                    this.$message.success("登录成功");
                });
            }

| 登录成功之后的token保存到sessionStorage中

window.sessionStorage.setItem("token",res.data.token);

| 保存好token之后跳转到首页

this.$router.push("/home");

从0到1开发测试平台(十)后端增加登录token返回

从0到1开发测试平台(九)后端对接口response的封装

从0到1开发测试平台(八)后端服务添加lombok第三方类库

从0到1开发测试平台(七)后端服务添加swagger第三方类库

从0到1开发测试平台(六)增加登录接口

从0到1开发测试平台(五)RESTful API接口设计标准及规范

从0到1开发测试平台(四)Controller+Service +Dao三层的功能划分

从0到1开发测试平台(三)利用vue cli创建前端vue项目

从0到1开发测试平台(二)springboot搭建常见问题

带你用java从0到1开发测试平台