uView——Interceptor过滤器


简介

  Interceptro过滤器包含:

    setConfig({}) 配置请求请求默认信息

    request:过滤请求

    response:过滤响应

 

意义:

  配置信息:让每次请求自动携带请求头

  请求:同上

  响应:不同状态码做出响应

 

配置:

  common下新建http.interceptor.js

  main.js:全局配置对象

 

请求过滤和响应过滤方法

  请求过滤

    // 不记忆,直接使用文档给的 
  Vue.prototype.$u.http.interceptor.request = (config) => { config.header.Token = 'xxxxxx';
      
     return config; }

    参数:

      config:配置对象

    返回值:config

    返回值意义:request获取到config对象

    作用:通过config对象。可以用config.header.content-type= "xxx",为上面配置的config赋上新请求头

  

  响应过滤

    Vue.prototype.$u.http.interceptor.response = (response) => {
       if(response.statusCode < 400 ){
      
      } }

    参数;

      response:响应json对象

    返回值:对象或者false

    返回值意义:对象回调给this.$u.get("xxx").then( (res) => {} )中的res对象。

    作用:对象回调给this.$u.get("xxx").then( (res) => {} )中的res对象。

	// 如果返回false,则会调用Promise的reject回调, // 并将进入this.$u.post(url).then().catch(res=>{})的catch回调中,res为服务端的返回值

使用


// http.interceptor.js
//
这里的vm,就是我们在vue文件里面的this,所以我们能在这里获取vuex的变量,比如存放在里面的token变量 const install = (Vue, vm) => { // 此为自定义配置参数,具体参数见上方说明 Vue.prototype.$u.http.setConfig({ baseUrl: '', // 请求的本域名 method: 'POST', dataType: 'json', // 设置为json,返回后会对数据进行一次JSON.parse() showLoading: true, // 是否显示请求中的loading loadingText: '请求中...', // 请求loading中的文字提示 loadingTime: 800, // 在此时间内,请求还没回来的话,就显示加载中动画,单位ms originalData: true, // 是否在拦截器中返回服务端的原始数据,-----原始数据指源json loadingMask: true, // 展示loading的时候,是否给一个透明的蒙层,防止触摸穿透 // 配置请求头信息 header: { 'content-type': 'application/json;charset=UTF-8' }, });
  // 请求过滤:自动添加请求头 Vue.prototype.$u.http.interceptor.request
= (config) => { } //响应过滤,对不同的状态作响应 Vue.prototype.$u.http.interceptor.response = (response) => { if( response.statusCode < 400 ){
       vm.$u.toast('验证失败,请重新登录');
       return false;
      }
      return response.data; } } export
default { install }

 

// main.js:作配置
.......................
....................... const app
= new Vue({ ...App }) // http拦截器,此为需要加入的内容,如果不是写在common目录,请自行修改引入路径 import httpInterceptor from '@/common/http.interceptor.js' // 这里需要写在最后,是为了等Vue创建对象完成,引入"app"对象(也即页面的"this"实例) Vue.use(httpInterceptor, app) app.$mount()

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM