VUE脚手架axios中 跨域 实例 并发 全局 拦截

VUE脚手架axios官方网址:

https://www.kancloud.cn/yunye/axios/234845

需要在文档安装 npm install axios 才能使用 axios

1.并发请求:

<template>

  <div id="app">


  </div>

</template>

<script>

import axios from 'axios'

export default {

  name: 'App',

  data(){

  return{

    url1:'https://cno..................',

    url2:'https://cno.........................'

  }

  },

  /* 执行多个并发请求 */

  created(){

    Promise.all([axios.get(this.url1),  axios.get(this.url2)])

    .then(res=>{

         console.log(res);

    })

    /* 和上面Promise 方法类似 但是Promise只返回一个数组 */

   axios.all(  [axios.get(this.url1),  axios.get(this.url2)] )

   .then( axios.spread( (res1,res2)=>{

     /* 两个请求都请求完毕了,再返回结果 */

       console.log(res1);

       console.log(res2);

   }))

  }

}

</script>

<style>

#app {

  font-family: Avenir, Helvetica, Arial, sans-serif;

  -webkit-font-smoothing: antialiased;

  -moz-osx-font-smoothing: grayscale;

  text-align: center;

  color: #2c3e50;

  margin-top: 60px;

}

</style>

2.跨域 实例 全局 拦截:

跨域:建立一个简单的js文档:

let http = require('http')

http.createServer((req,res)=>{

    /* 这句话是允许跨域用的 */

    // res.setHeader('Access-Control-Allow-Origin','*')

    /* 下面是后端返回的结果 */

    res.end('yousuccess')

    /* 3000是端口 */

}).listen(3000,function(){

    console.log('server start...')

})

在vue.config.js文件中配置一下:

const { defineConfig } = require('@vue/cli-service')

module.exports = defineConfig({

  transpileDependencies: true,

  devServer: {

    proxy: {

      '/api': {

        target: 'http://localhost:3000/'

      }

    }

  }

})

主文件App.vue:

<template>

  <div id="app">

   <button @click="login">登 录</button>

   <button @click="getUser">获取用户</button>

   <button @click="getList">所有权限列表</button>

   <child-a></child-a>

  </div>

</template>

<script>

import axios from 'axios'

import ChildA from '@/components/ChildA.vue'

export default {

  name: 'App',

  components:{

   ChildA

  },

  data(){

  return{

    instance:null

  }

  },

  created(){

    /* axios.get('/api')

    .then(res=>{

     console.log(res);

    }) */


    //* 自定义配置新建一个 axios 实例 */

    //* 设置了baseURL 使用了这个instance实例都不用把url写全,直接写路径(例如:login)即可 */

    /* this.instance = axios.create({

      baseURL:'http://time.......................',

      //如果请求花费了超过'timeout'时间,请求将被中断

      timeout:3000,

      //给使用instance这个实例的都配置上Headers

      headers:{

           'Authorization':localStorage.token

         }

    }) */

    /* axios 全局配置基本路径和请求头 */

    axios.defaults.baseURL = 'http://tim................................',

    axios.defaults.headers.common['Authorization'] = localStorage.token,

    axios.defaults.timeout=3000;


    //如果想局部配置 请创建一个实例instance通过实例调接口

    //全局配置 添加请求拦截器

    //每次发送接口都会进行拦截

    axios.interceptors.request.use(function (config) {

      //console.log('config',config);

      //在请求拦截时候 添加请求头也是可以的

      config.headers.Authorization = localStorage.token

      //必须把config return  出去

      return config

    },function(error) {

      //对请求错误做些什么

      return Promise.reject(error)

    });

    //添加响应拦截器

    //只要请求有相应 都会先走一遍响应拦截器

    axios.interceptors.response.use(function (response) {

      //对响应数据做点什么

      console.log('response',response);

      //可以同意给返回数据 再添加属性和值

      response.data.msg = 'VUE好好学'

      //response 也是必须要return出去的

      //可以在响应拦截里面直接把数据data返回出去

      return response.data

    },function(error) {

         //对请求错误做些什么

      return Promise.reject(error)

    })

  },

  mounted(){

   /* 获取元素dom使用,mounted里面dom加载完毕 */

  },

  methods:{

    login(){

      /* this.instance */axios.post('login',{

        username:'admin',

        password:'123456'

      })

      .then(res=>{

        console.log(res.data);

        localStorage.token = res.data.token

      })

    },

    getUser(){

     axios.get('users',{

        params:{

          pagenum:1,

          pagesize:5

        },

        /* 在get配置请求中这样配置 */

        /*  headers:{

           'Authorization':localStorage.token

         } */

      })

      .then(res=>{

       console.log(res);

      })

    },

    getList(){

      axios.get('right/list')

      .then(res=>{

        console.log(res);

      })

    }

  }


}

</script>

<style>

#app {

  font-family: Avenir, Helvetica, Arial, sans-serif;

  -webkit-font-smoothing: antialiased;

  -moz-osx-font-smoothing: grayscale;

  text-align: center;

  color: #2c3e50;

  margin-top: 60px;

}

</style>

也可以在main.js文件中设置全局axios:

import Vue from 'vue'

import App from './App.vue'

import axios from 'axios'

Vue.config.productionTip = false

/* 在入口main.js文件导入axios

   并挂载到Vue构造函数的原型下 目的在供所有Vue组件使用

    这样写就不用每个vue页面都导入axios */

    Vue.prototype.$axios = axios;

new Vue({

  render: h => h(App),

}).$mount('#app')



©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容