requset页面的代码逻辑

基地址 :

//引入axios
import axios from 'axios';
//vuex
// import store from '../store/index';
//配置基准地址
const Serve = axios.create({
    baseURL: 'http://47.99.166.157:3000',
    // transformRequest: [function (data) {
    //     try {
    //         return jsonBig.parse(data)
    //     } catch (err) {
    //         return data
    //     }
    // }],
    timeout: 5000,
})

//抛出serve
export default Serve

main.js引入路径:

//引入基准路径
import axios from './utils/reques';

然后使用网络请求的数据:

  请求头的设置和请求拦截:

import axios from "axios";
import qs from "querystring";
axios.defaults.timeout = 60000;
axios.defaults.baseURL = window.apiHost;  //window.apiHost可以在main.js里进行设置
axios.defaults.withCredentials = false;

axios.interceptors.request.use(
  config => {
    if (config.method === "POST") {
      config.data = qs.stringify(config.data, { arrayFormat: "indices" });
    }
    //当使用Ie浏览器的时候,可能会出现数据更新了,但是接口请求数据不刷新的情况,加上下面这段代码即可
    if (config.method === 'get' || config.method === 'GET') {
      config.params = {
        _t: Date.parse(new Date()) / 1000,
        ...config.params
      }
    }
    if (!config.headers["Content-Type"]) {
      config.headers["Content-Type"] = "application/json;utf-8";
    }
	if (localStorage.getItem("userInfo")){
		var userinfo=localStorage.getItem("userInfo");
		config.headers["Authorization"]="Bearer "+JSON.parse(userinfo).Token
	}
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);
export default axios;

拦截器:

公共文件

文件路径和名称:utils/api.js

引入

import axios from "axios";
import { Message } from 'element-ui';
import router from "../router";//在拦截器中引入了router,在router中,配置了首先要转向的页面

拦截器
如果成功调用了后端接口 

  //  后端返回  

 确定是调用了后端

     如果,后端返回500、401、403,消息框提示(Messsage.error)后端返回的提示信息,因为是业务逻辑错误,所以返回空

     如果,有返回信息,消息框显示成功信息

  返回成功的数据

如果没有调用到后端

   后端返回504、404

     消息框提示服务器被吃了( ╯□╰ )

   后端返回403

     提示没权限

    后端返回401

      提示尚未登录,请登录

      路由替换成根路径

    判断后端返回的错误应答data是否有信息

       如果有信息,消息框提示data.message

       否则,消息框提示未知错误

    返回空

请求
定义前置路径

导出定义的post请求,参数是url\params

返回 axios

方法:post

data:params


前端


页面打开,就加载updateCaptcha方法,方法中获取到验证码图片的地址,通过get方法。

提交登录调用了post方法

执行这个方法,就会调用postRequest公共方法

跨域

token过期:

当我们操作某个需要token作为请求头的接口时,返回的数据错误error.response.status === 401,说明我们的token已经过期了。

阻拦响应器中配置:

// 阻拦响应器
request.interceptors.response.use(function (response) {
  return response
}, async function (error) {
  if (error.response && error.response.status === 401) {
    // token续签方式1:
    //清空当前vuex保存的token(我们这的vuex和本地已经建立了关系,相当于也清空了本地token)
     store.commit('upUser', '')
     console.log(router.currentRoute.fullPath)// 当前路由的完整路径(#后面的)
      //这里我们采用?path=的方式保存当前浏览页面的完整路径,
    // push()会产生历史记录 而replace不会有历史记录
     router.push({ path: `/login?path=${router.currentRoute.fullPath}` })
 
  }
  return Promise.reject(error)
})

再登入组件中给登入功能函数添加:

 this.$router.replace({
          path: this.$route.query.path || '/'
        })

// 1.点击登入
    async onSubmit () {
      try {
        const { data: res } = await loginAPI(this.user)
        //登录成功
        // 不严谨的返回上次浏览的页面
        // this.$router.back()
        // 推荐方式:
        // 登录后, 判断有未遂地址(有未遂地址的情况是:token过期,在阻拦响应器中实现对未遂地址的保存), 登入成功后跳转到未遂地址, 否则去/路径(跳到首页--这种情况是:用户主动前往登入页面的登入,没有未遂地址,登入成功后直接前往首页)
        // replace不会产生路由历史记录
        this.$router.replace({
          path: this.$route.query.path || '/'
        })
        // 存储获取过来的token
        this.$store.commit('upUser', res.data)
      } catch (err) {
        console.log(err)
        if (err.response.status === 400) {
          this.$toast.fail('手机号或验证码错误')
        } else {
          this.$toast.fail('登入失败,请稍后再试') // 可能由于网络问题导致的登入失败
        }
      }
    },

个人界面编辑:

 

猜你喜欢

转载自blog.csdn.net/PCthedream/article/details/130659325