Преглед на файлове

登录信息路由拦截

yangwei преди 7 години
родител
ревизия
e463f44f92
променени са 3 файла, в които са добавени 83 реда и са изтрити 71 реда
  1. 33 40
      src/features/login/Login.vue
  2. 19 3
      src/router.js
  3. 31 28
      src/utils/axios.js

+ 33 - 40
src/features/login/Login.vue

@@ -7,30 +7,33 @@
         <font size="5">远程教育网络考试</font>
         <Row>
             <Col>        
-                <Form ref="formInline" :model="formInline" :rules="ruleInline">
+                <Form ref="loginForm" :model="loginForm" :rules="loginFormRule">
                   <FormItem prop="accountType">
-                          <RadioGroup size="large" v-model="formInline.accountType">
+                          <RadioGroup size="large" v-model="loginForm.accountType">
                               <Radio label="STUDENT_CODE">学生</Radio>
                               <Radio label="STUDENT_IDENTITY_NUMBER">身份证号</Radio>
                           </RadioGroup>                
                   </FormItem>
-                  <FormItem prop="user">
-                      <Input type="text" size="large" v-model="formInline.user" placeholder="登录账号">
+                  <FormItem prop="accountValue">
+                      <Input type="text" size="large" v-model="loginForm.accountValue" placeholder="登录账号">
                           <Icon type="ios-person-outline" slot="prepend"></Icon>
                       </Input>
                   </FormItem>
                   <FormItem prop="password">
-                      <Input type="password" size="large" v-model="formInline.password" placeholder="密码">
+                      <Input type="password" size="large" v-model="loginForm.password" placeholder="密码">
                           <Icon type="ios-locked-outline" slot="prepend"></Icon>
                       </Input>
                   </FormItem> 
                   <FormItem>
                       <Row>
+                        <Col span="18" offset ="3" v-if="errorInfo!==''">
+                             <Alert type="error" show-icon>{{errorInfo}}</Alert>
+                        </Col>
                         <Col span="12" style="padding-right: 5px;">
-                              <Button type="error" size="large" @click="login('formInline')">登录</Button>
+                              <Button type="error" size="large" @click="login('loginForm')">登录</Button>
                         </Col>
                         <Col span="12" style="padding-left: 5px;">
-                              <Button type="ghost" size="large" @click="close('formInline')">关闭</Button>
+                              <Button type="ghost" size="large" @click="close('loginForm')">关闭</Button>
                         </Col>
                       </Row>
                   </FormItem>
@@ -48,17 +51,15 @@
 <script>
 export default {
   data() {
-    debugger;
     return {
-      domain: this.$route.query.domain || "",
-      formInline: {
+      errorInfo: "",
+      loginForm: {
         accountValue: "",
         password: "",
-        loginType: "STUDENT_CODE",
         accountType: "STUDENT_CODE"
       },
-      ruleInline: {
-        user: [
+      loginFormRule: {
+        accountValue: [
           {
             required: true,
             message: "请填写登录账号",
@@ -71,41 +72,33 @@ export default {
             message: "请填写密码",
             trigger: "blur"
           }
-          // {
-          //   type: "string",
-          //   min: 6,
-          //   message: "The password length cannot be less than 6 bits",
-          //   trigger: "blur"
-          // }
         ]
       }
     };
   },
   methods: {
-    login(name) {
-      // this.$http({
-      //   method: "get",
-      //   url: "/api/comments",
-      //   params: { a: 1 },
-      //   data: {
-      //     name: "virus"
-      //   },
-      //   message: this.$Message
-      // });
-
-      this.$get("/api/comments", {})
-        .then(res => {
-          debugger;
-          console.log(res);
-        })
-        .catch(response => {
-          debugger;
-          console.log(response);
-        });
+    async login(name) {
+      this.loginForm["domain"] = this.$route.query.domain || "";
+      let repPara = this.loginForm;
+      const response = await this.$http.post(
+        "/api/ecs_core/auth/login",
+        repPara
+      );
+      let data = response.data || response.response.data;
+      if (data.token) {
+        this.errorInfo = "";
+        //缓存用户信息
+        window.localStorage.setItem("token", data.token);
+        window.localStorage.setItem("key", data.key);
+      } else {
+        this.errorInfo = data.desc;
+        window.localStorage.removeItem("token");
+        window.localStorage.removeItem("key");
+      }
 
+      console.log(response);
       this.$refs[name].validate(valid => {
         if (valid) {
-          this.$Message.success("Success!");
         } else {
           this.$Message.error("Fail!");
         }

+ 19 - 3
src/router.js

@@ -8,8 +8,7 @@ import OnlineExamHome from "./features/OnlineExam/OnlineExamHome.vue";
 import Login from "./features/login/Login.vue";
 
 Vue.use(Router);
-
-export default new Router({
+let router = new Router({
   mode: "history",
   routes: [{
       path: "/",
@@ -41,4 +40,21 @@ export default new Router({
       component: NotFoundComponent
     }
   ]
-});
+});
+
+router.beforeEach((to, from, next) => {
+  debugger
+  if (to.path === "/login") {
+    next();
+  } else {
+    if (!window.localStorage.getItem("token")) {
+      next({
+        path: "/login"
+      })
+    } else {
+      next();
+    }
+  }
+});
+
+export default router;

+ 31 - 28
src/utils/axios.js

@@ -1,17 +1,23 @@
 import Vue from "vue";
 import Axios from "axios";
+import router from "../router";
 //axios配置 start
 
 //请求拦截
 let $Message;
 Axios.interceptors.request.use(
   config => {
-    // 在发送请求之前做某件事
-
-    // 若是有做鉴权token , 就给头部带上token
-    // if (localStorage.token) {
-    // config.headers.Authorization = localStorage.token;
+    // if (window.localStorage.getItem("token")) {
+    //   Axios.defaults.headers.common["token"] = response.data.token;
+    //   Axios.defaults.headers.common["key"] = response.data.key;
+    // } else {
+    //   if (config.url != "/api/ecs_core/auth/login") {
+    //     router.push({
+    //       name: 'login'
+    //     })
+    //   }
     // }
+
     $Message = config.message;
     return config;
   },
@@ -34,8 +40,7 @@ Axios.interceptors.response.use(
     // 这里是返回状态码不为200时候的错误处理
     let status = error.response.status;
     // 登录失效 跳转登录页面
-    if (status == 403 || status == 401) {
-    }
+    if (status == 403 || status == 401) {}
     return Promise.resolve(error);
   }
 );
@@ -54,25 +59,23 @@ let ajax = (url, params, type = "json", method = "get", thisObj) => {
   let getData = method === "get" ? params : {};
   let postData = method === "post" ? params : {};
   let headers =
-    type == "form"
-      ? {
-          "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"
-        }
-      : {
-          Accept: "application/json",
-          "Content-Type": "application/json; charset=UTF-8"
-        };
+    type == "form" ? {
+      "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"
+    } : {
+      Accept: "application/json",
+      "Content-Type": "application/json; charset=UTF-8"
+    };
 
-  return new Promise(function(resolve, reject) {
+  return new Promise(function (resolve, reject) {
     Axios({
-      method: method,
-      url: url,
-      params: getData,
-      data: postData,
-      headers: headers,
-      withCredentials: true,
-      message: thisObj.$Message
-    })
+        method: method,
+        url: url,
+        params: getData,
+        data: postData,
+        headers: headers,
+        withCredentials: true,
+        message: thisObj.$Message
+      })
       .then(res => {
         let status = res.status;
         if (status >= 200 && status < 300) {
@@ -98,19 +101,19 @@ let ajax = (url, params, type = "json", method = "get", thisObj) => {
 Vue.prototype.$http = Axios;
 
 // get请求
-Vue.prototype.$get = function(url, params) {
+Vue.prototype.$get = function (url, params) {
   return ajax(url, params, "", "get", this);
 };
 
 // post请求
-Vue.prototype.$post = function(url, params, type) {
+Vue.prototype.$post = function (url, params, type) {
   return ajax(url, params, type, "post", this);
 };
 
 export default {
-  install: function(Vue, Option) {
+  install: function (Vue, Option) {
     Object.defineProperty(Vue.prototype, "$http", {
       value: Axios
     });
   }
-};
+};