Browse Source

请求工具新增通用请求方法

yangxiao 3 years ago
parent
commit
f5a7fa1498
3 changed files with 111 additions and 40 deletions
  1. 81 11
      src/api/axios.js
  2. 26 25
      src/assets/js/login.js
  3. 4 4
      src/assets/js/main.js

+ 81 - 11
src/api/axios.js

@@ -4,6 +4,75 @@ import store from '@store/index'
 import axios from 'axios'
 import { Message } from 'element-ui';
 
+/**
+ * 通用请求函数
+ * @param {Object} options 详细配置项,使用方法与所有配置项说明如下:
+
+  this.API.requestData({
+    isMust: true, // 请求是否携带 token ,默认为 true ,可缺省
+    method: "GET", // 请求方式,默认为 GET ,可缺省
+    subUrl: "api/repassword", // 请求接口地址,必传项
+    timeout: 3000, // 请求超时时间,默认 3s ,可缺省
+    data: { name: "admin", pasword: "123456" }, // 请求所携带参数,默认为空,可缺省
+    success (res) {
+      // 请求成功的回调
+    },
+    fail (error) {
+      // 请求失败的回调
+    }
+  });
+
+ */
+export function requestData (options) {
+  return new Promise((resolve, reject) => {
+
+    // 包装请求头
+    let headers = {
+      'Content-Type': 'application/x-www-form-urlencoded',
+    };
+
+    const isMust = (options.isMust == true || options.isMust == false) ? options.isMust : true;
+
+    if (isMust) headers.authToken = localStorage.getItem('authToken');
+
+    // 创建请求实例
+    const XHRReq = axios.create({
+      headers,
+      baseURL: process.env.VUE_APP_API_URL || '/api/',
+      timeout: options.timeout || 3000,
+    });
+
+    // 请求拦截器
+    XHRReq.interceptors.request.use(
+      config => {
+        return config;
+      },
+      err => {
+        return Promise.reject(err);
+      }
+    );
+
+    let params = new URLSearchParams();
+    for (let key in (options.data || {})) {
+      params.append(key, options.data[key]);
+    }
+
+    httpService({
+      url: options.subUrl,
+      method: options.method || 'GET',
+      params,
+    }).then(response => {
+      if (response.code === 200) {
+        options.success(resolve(response));
+      } else {
+        Message.error(response.message || ("请求出错[" + response.code + "]"));
+      }
+    }).catch(error => {
+      options.fail(reject(error));
+    });
+  });
+}
+
 // 创建axios实例
 const httpService = axios.create({
   withCredentials: false, // 允许携带cookie
@@ -41,7 +110,7 @@ const httpService_L = axios.create({
 // httpService.defaults.withCredentials = true; // 表示跨域请求时是否需要使用凭证
 httpService_L.interceptors.request.use(
   config => {
-    if(localStorage.getItem('authToken')){
+    if (localStorage.getItem('authToken')) {
       config.headers.authToken = localStorage.getItem('authToken');
     }
     return config;
@@ -53,7 +122,7 @@ httpService_L.interceptors.request.use(
 // http request 拦截器
 httpService.interceptors.request.use(
   config => {
-    if(localStorage.getItem('authToken')){
+    if (localStorage.getItem('authToken')) {
       config.headers.authToken = localStorage.getItem('authToken');
     }
     return config;
@@ -68,10 +137,10 @@ httpService_L.interceptors.response.use(
     const {
       data
     } = response;
-    if(data.code === 200){
+    if (data.code === 200) {
 
     }
-    else{
+    else {
       // let rqData = JSON.parse(response.config.data); // 请求数据
       // console.error(BASE.getNowTime(), rqData.interfaceid+":"+data.message)
       Message.warning(data.message);
@@ -140,10 +209,10 @@ httpService.interceptors.response.use(
     const {
       data
     } = response;
-    if(data.code === 200){
+    if (data.code === 200) {
 
     }
-    else{
+    else {
       // let rqData = JSON.parse(response.config.data); // 请求数据
       // console.error(BASE.getNowTime(), rqData.interfaceid+":"+data.message)
       Message.warning(data.message);
@@ -213,7 +282,7 @@ httpService.interceptors.response.use(
  *  url: 接口地址
  *  params: 参数,格式如下
  * */
-export function get(url, params = {}) {
+export function get (url, params = {}) {
   return new Promise((resolve, reject) => {
     httpService({
       url: url,
@@ -233,7 +302,7 @@ export function get(url, params = {}) {
  *  url: 接口地址
  *  params: 参数,格式如下
  * */
-export function post(url, params = {}) {
+export function post (url, params = {}) {
 
   return new Promise((resolve, reject) => {
     httpService({
@@ -254,7 +323,7 @@ export function post(url, params = {}) {
  *  url: 接口地址
  *  params: 参数,格式如下
  * */
-export function get_L(url, params = {}) {
+export function get_L (url, params = {}) {
   return new Promise((resolve, reject) => {
     httpService_L({
       url: url,
@@ -274,7 +343,7 @@ export function get_L(url, params = {}) {
  *  url: 接口地址
  *  params: 参数,格式如下
  * */
-export function post_L(url, params = {}) {
+export function post_L (url, params = {}) {
 
   return new Promise((resolve, reject) => {
     httpService_L({
@@ -293,7 +362,7 @@ export function post_L(url, params = {}) {
  *  url: 接口地址
  *  params: 参数,格式如下
  * */
-export function postL(url, params = {}) {
+export function postL (url, params = {}) {
 
   return new Promise((resolve, reject) => {
     axios.create({
@@ -323,4 +392,5 @@ export default {
   post,
   post_L,
   postL,
+  requestData
 }

+ 26 - 25
src/assets/js/login.js

@@ -1,37 +1,38 @@
-import { mapMutations} from 'vuex'
+import { mapMutations } from 'vuex'
 export default {
-  data() {
+  data () {
     return {
-      username:'',
-      password:'',
+      username: '',
+      password: '',
     }
   },
   components: {
   },
-  created() {
+  created () {
   },
-  
+
   methods: {
     ...mapMutations("user", ["SET_TOKEN"]),
-    login(){
+    login () {
       var digital = new URLSearchParams();
-      digital.append("username","admin"),
-      digital.append("password","admin"),
-      this.API.post("/admin/loginvue", digital).then((res) => {
-       const {data,code} = res;
-       debugger
-       
-       console.log(localStorage.getItem('authToken'));
-       if(code == 200){
-				this.SET_TOKEN(data);
-				this.$message({
-          message: '登陆成功',
-          type: 'success'
+      digital.append("username", "admin"),
+        digital.append("password", "admin"),
+        this.API.post("/admin/loginvue", digital).then((res) => {
+          const { data, code } = res;
+          debugger
+
+          console.log(localStorage.getItem('authToken'));
+          if (code == 200) {
+            this.SET_TOKEN(data);
+            this.$message({
+              message: '登陆成功',
+              type: 'success'
+            });
+            this.$router.push('/'); // 跳转到首页
+          } else {
+            this.$message.error('登录失败');// ui弹窗提示
+          }
         });
-         this.$router.push('/'); // 跳转到首页
-			} else {
-        this.$message.error('登录失败');// ui弹窗提示
-			}
-      });
     }
-  }}
+  }
+}

+ 4 - 4
src/assets/js/main.js

@@ -1,7 +1,7 @@
 import menuData from "@jsonData/menu.json" //动态导入
 import menuZj from "@components/common/menu"
 export default {
-  data() {
+  data () {
     return {
       menuIndex: '1', // 菜单默认选中项
       menu: [], // 菜单数据
@@ -10,19 +10,19 @@ export default {
   components: {
     menuZj
   },
-  created: function() {
+  created: function () {
     this.init();
   },
   methods: {
     // 初始化
-    init() {
+    init () {
       this.menu = menuData.menu;
       // this.API.get('/powercompare/windfarmAjax').then(res => {
       //   console.log(res)
       //   // if (res.code === 200) {
       //   //   this.eqType = this.BASE.cascaderBugRepair(res.data.result);
       //   // }
-  
+
       // });
     },
   }