vue 如何发起网络请求 之 axios


 

1
 
1
2
3
4
5
6
7
8
9
10
// axios 请求  在main.js里边写入
import  Axios from  'axios'
 
// 配置请求信息
var  $http = Axios.create({
   baseURL:  '配置路径' ,
   timeout:  '3000' ,   //超时时间
   headers: { 'X-Custom-Header' 'foobar' }   //请求头
})
Vue.prototype.$http = $http
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// 方法调用,回调,post , 基于es6 promise
  methods: {
    getNum:  function () {
       var  data = { TenantID:  "0" }
       this .$http.post( "请求路径-方法1" , data ) .then(res => {
          console.log(res)  //返回方法1的值
                 var  data1 =  { TenantID: res.data.Code }  //方法1 的返回值作为参数传递 res.data.Code
                 this .$http.post( "请求路径-方法2" , data1 )
                 .then(res1 => {
                     console.log(res.data)  //同样可以使用方法1的返回值
                     console.log(res1)   //返回方法2的值
                 })
             })
             . catch ( function (error) {
                 console.log(error)
         })
     }
//需要使用箭头函数,否则 this.$http 中的this 指向window,会报 $http undefined
//另外也可以在当前组件 import axios from 'axios'  引入axios 包
//将 this.$http 替换 为 axios  结果一样

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
axios 拦截器
 
你可以截取请求或响应在被 then 或者  catch  处理之前
 
//添加请求拦截器
axios.interceptors.request.use( function (config){
      //在发送请求之前做某事
      return  config;
    }, function (error){
      //请求错误时做些事
      return  Promise.reject(error);
    });
  
//添加响应拦截器
axios.interceptors.response.use( function (response){
      //对响应数据做些事
      return  response;
    }, function (error){
      //请求错误时做些事
      return  Promise.reject(error);
    });<br>
以后可能需要删除拦截器。
var  myInterceptor = axios.interceptors.request.use( function  () { /*...*/ });
axios.interceptors.request.eject(myInterceptor);<br>
你可以将拦截器添加到axios的自定义实例。
var  instance = axios.create();
instance.interceptors.request.use( function  () { /*...*/ });<br>
处理错误
axios.get( '/ user / 12345'
    . catch function (error){
      if (error.response){
        //请求已发出,但服务器使用状态代码进行响应
        //落在2xx的范围之外
        console.log(error.response.data);
        console.log(error.response.status);
        console.log(error.response.headers);
      else  {
        //在设置触发错误的请求时发生了错误
        console.log( 'Error' ,error.message);
      }}
      console.log(error.config);
    });
您可以使用validateStatus配置选项定义自定义HTTP状态码错误范围。
 
axios.get( '/ user / 12345' ,{
    validateStatus: function (status){
      return  status < 500;  //仅当状态代码大于或等于500时拒绝
    }}
})


免责声明!

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



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