axios get post all 请求 数据

数据请求

数据请求在前端开发中的使用有两种形式
使用原生javascript提供的数据请求
     ajax( 四部曲,一般需要我们结合Promise去封装,使用不是很便利,但是效率很高 )
    fetch( 本身结合了Promise,并且已经做好了封装,可以直接使用 )

axios介绍

Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。
特性:
1、从浏览器中创建 XMLHttpRequests
2、从 node.js 创建 http 请求
3、支持 Promise API
4、拦截请求和响应
5、转换请求数据和响应数据
6、取消请求
7、自动转换 JSON 数据
8、客户端支持防御 XSRF 

代码  

<template>
  <div>
    <button @click="getData">获取数据</button>
  </div>
</template>
  
<script>
import axios from 'axios';

export default {
  methods: {
    getData() {

      // get 正常接口数据请求
      axios.get("https://jsonplaceholder.typicode.com/posts/55")  //路径换成真的
        .then(response => {                             //监听返回
          console.log(response.data, 'get 正常接口数据请求');
        })
        .catch(error => {
          console.log(error, '失败');
        });


      // get 携带数据请求 
      axios.get('https://jsonplaceholder.typicode.com/comments/4', {
        params: {                                                // 携带数据
          name: 'wendy',
          age: 18
        },
        timeout: 3000, // 单个请求配置的超时时间
      })
        .then((res) => {
          console.log(res.data, 'get 携带数据请求 ')
        });

      // -------------------------------------------------------------------------------------


      // post 正常接口数据请求
      axios.post('https://jsonplaceholder.typicode.com/albums?userId=4')  //路径换成真的
        .then(response => {                             //监听返回
          console.log(response.data, 'post 正常接口数据请求');
        })
        .catch(error => {
          console.log(error, '失败');
        });

      // post 携带数据请求 
      axios.post('https://jsonplaceholder.typicode.com/albums?userId=4', {
        data: {
          name: 'why',
          age: 12332328
        }
      })
        .then((res) => {
          console.log(res.data,'post 携带数据请求 ')
        });

      // -------------------------------------------------------------------------------------
      // axios  统一请求 
      axios.all([
        axios.get('https://jsonplaceholder.typicode.com/albums?userId=4'),
        axios.post('https://jsonplaceholder.typicode.com/todos?userId=4')
      ])
        .then((res) => {
          // 返回的res是个response的数组
          console.log(res[0].data,' axios  统一请求 ')
          console.log(res[1].data ,' axios  统一请求 ')
        })

      // axios  统一请求   携带数据请求
      axios.all([
        axios.get('https://jsonplaceholder.typicode.com/albums?userId=4', { params: { name: 'why', age: 18 } }),
        axios.post('https://jsonplaceholder.typicode.com/todos?userId=4', { params: { name: 'why', age: 18 } }),
      ])
        .then((res) => {
          // 返回的res是个response的数组
          console.log(res[0].data ,'axios  统一请求   携带数据请求')
          console.log(res[1].data ,'axios  统一请求   携带数据请求')
        })

    }
  }
}
</script>

假数据

 --------------------------------------------------------------------------------------------------------------------------------

axios 数据请求拦截

1-1 应用场景:

请求拦截器用于在接口请求之前做的处理,比如为每个请求带上相应的参数(token,时间戳等)
返回拦截器用于在接口返回之后做的处理,比如对返回的状态进行判断 token是否过期和错误返回

1-2 拦截器的使用

1、 在src目录下建立api文件夹
2、 文件夹内建立axios.js文件,进行接口请求的初始化配置

概述:什么是请求响应拦截器?

所谓的拦截器就是 在请求或响应被 then 或 catch 处理前拦截它们。简单的来说就是,当我们发起一个请求前,如果设置了请求拦截器,则会优先执行拦截器里面的方法,我们可以在请求正式发向后端服务器之前,对此次的请求 进行“二次加工”, 然后再放行给后端服务器,同理,响应拦截器就是对请求回来的数据,做统一处理,如解构等,然后再把处理好的数据,返回给页面,页面就可以直接收到,处理好的数据,同时,拦截器还能够对,错误请求或错误响应,做出统一的管理提示,可以理解成,拦截器就是我们和服务器交互请求时的,安全保障员。

 --------------------------------------------------------------------------------------------------------------------------------

 Axios 构造函数,通过this关键字指定的属性,另外还有默认配置对象defaults。

 第二,request哪来的?
this.interceptors 是个对象,包含两个属性request和response。

第三,use方法哪来的?
request属性对应的值是一个 InterceptorManager实例对象,use是其中的方法。

安装

npm install axios -g

 main.js

import Vue from 'vue';
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import App from './App.vue';
import echarts from 'echarts'  //引入echarts

import axios from 'axios'//引入
Vue.prototype.$http = axios //正确的使用

Vue.use(ElementUI);
 
new Vue({
  el: '#app',
  echarts,
  render: h => h(App)
});

代码

<template>
  <div>
    <button @click="getData">获取数据</button>
  </div>
</template>
  
<script>
import axios from 'axios';

export default {
  methods: {
    getData() {

         // //2.1 请求拦截器
      // axios.interceptors.request.use(
      //   function (config) {
      //     //在请求之前做些什么
      //     return config
      //   },
      //   function (error) {
      //     //对请求错误做些什么
      //     return Promise.reject(error)
      //   }
      // )

      // //2.2 响应拦截器
      // axios.interceptors.response.use(
      //   function (response) {
      //     //对响应数据做点什么
      //     return response
      //   },
      //   function (error) {
      //     //对响应错误做点什么
      //     return Promise.reject(error)
      //   }
      // )
//----------------------------------------------------------------

       
      // 设置请求拦截器  config 配置对象  获取 然后进行判断  或者修改
      axios.interceptors.request.use(function one(config) {   //请求拦截 数据
        console.log('请求拦截器 成功 - 1号');         //成功输出
        // if (this.name === 'a') { // 请求拦截  判断错误 输出   可以在这进行需要的捕获拦截
        //   console.log('请求拦截器 成功 - 1号');
        // }
        return config;  //返回
      }, function one(error) {
        console.log('请求拦截器 失败 - 1号');
        return Promise.reject(error);    // axios 返回的是 promise数据  
      });

      // 设置响应拦截器
      axios.interceptors.response.use(function (response) {  //响应拦截器数据
          console.log('响应拦截器 成功 1号');  //成功响应
          return response;              //返回
      }, function (error) {
        if (error.response.status === 401) {
          console.log('401错误')
        } else {
          return Promise.reject(error)
        }
      });

      //发送请求
      axios({
        method: 'GET',
        url: "https://jsonplaceholder.typicode.com/posts/55"
      }).then(response => {
        console.log(response, '成功了');
      });



    }
  }
}
</script>

axios全局请求拦截中如何取消请求 axios请求拦截原理_axios全局请求拦截中如何取消请求

 

axios全局请求拦截中如何取消请求 axios请求拦截原理_axios全局请求拦截中如何取消请求_02

https://www.jb51.net/article/273205.htm

 -------------------------------------------------------------------------------------------------------------------------------

axios 封装

index.vue

<template>
  <div>
    <button @click="getData">获取数据</button>
  </div>
</template>
  
<script>
// 引入  http 这个是request 暴露出来的
import http from '../components/request'
export default {
  methods: {
    getData() {

      // 请求 路径  监听 
      http.post("https://jsonplaceholder.typicode.com/comments").then(r => {
        console.log(r, 'asasasa')   //至于为啥子  undefined  我也不知道  没搞清楚
      }) 

      http.get("https://jsonplaceholder.typicode.com/todos?userId=4").then(r => {
        console.log(r, 'asasasa')
      })

       // 请求 路径  监听   携带数据 
      http.get("https://jsonplaceholder.typicode.com/comments", {
        firstName: 'Fre撒旦水水水水水水水水水水水水水水d',
        lastName: 'Flintstone'
      })
        .then(function (response) {
          console.log(response,'asa');
        })
      
    }
  }
}
</script>

main.js  可以引入  可以不引入   看你定义情况

import Vue from 'vue';
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import App from './App.vue';
import echarts from 'echarts'  //引入echarts

import http from './components/request'
Vue.prototype.http = http

import axios from 'axios'//引入
Vue.prototype.http = axios //正确的使用

Vue.use(ElementUI);
 
new Vue({
  el: '#app',
  echarts,
  render: h => h(App)
});

request.js

import axios from "axios";
 
//1.允许创建axios实例
const instance = axios.create({
  baseURL: "http://jsonplaceholder.typicode.com/",
  // 表示超时事件 如果超过这个时间 就不再请求 进行报错
  // Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'data')
  timeout: 5000000,
  //请求头
  headers: { "Content-Type": "application/json " },
  //会在原先传的参数的情况下 前面添加一项 可以用于传token
  // get请求使用
  params: {
    token: localStorage.getItem("token"),
  },
  // post请求使用
  data: {
    token: localStorage.getItem("token"),
  },
});
 
// 2.拦截器
// 请求拦截器
// 在发送请求之前执行这个函数
instance.interceptors.request.use(
  function (config) {
    // 参数config是要发送给后端的所有内容
    // 在发送请求之前统一做一些事情 比如发送token 更换请求头
    // console.log(config);
 
    // 如果是上传文件的请求 更改请求头
    // if (config.url === "/file/upload") {
    //   config.headers = ...
    // }
    return config;
  },
  (error) => {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);
 
// 响应拦截器
// 在刚好接收数据的时候执行
instance.interceptors.response.use(
  function (response) {
    console.log(response); //数据对象
    // 对响应数据做点什么
    //?  可以在这里过滤数据 要哪个数据返回哪个数据
    //?  可以在这处理状态码
    if (response.status === 200) {
      return response; //这里return出去的东西是return导get或者post方法的.then方法里
    } else if (response.status === 500) {
      // 抛错导catch
      // 这里404错误无法处理
      throw new Error("505 服务器端错误...");
    }
  },
  function (error) {
    // 对响应错误做点什么
    return Promise.reject(error);
  }
);
 
const http = {
  // 参数可以直接传递 params直接是对象
  get(url, params) {
    //使用实例请求 可以直接自动拼接baseURL
    return instance
      .get(url, {
        params: params,
      })
      .then((res) => {
        if (res.data.status === 0) {
          return res;
        }
      })
      .catch((err) => {
        //   捕获错误信息 timeout of 1000ms exceeded  捕获之后可以将这个换成轻提示
        // console.log(err.message);
        if (err.message === "timeout of 1000ms exceeded") {
          alert("请求超时");
        }
        alert("服务器端错误");
      });
  },
  post(url, data) {
    return instance
      .post(url, data)
      .then((response) => {
        return response;
      })
      .catch((error) => {
        console.log(error);
      });
  },
};
 
export default http;

axios全局请求拦截中如何取消请求 axios请求拦截原理_axios全局请求拦截中如何取消请求_03

 我在运行的时候出现一个报错  虽然不影响啥  但是要是 讨厌的话 就可以注销一下

GET http://192.168.0.102:8080/sockjs-node/info?t=1647433830643 net::ERR_CONNECTION_REFUSED解决方法

找到这个文件:

…/node_modules/sockjs-client/dist/sockjs.js

 

axios全局请求拦截中如何取消请求 axios请求拦截原理_前端框架_04

 保存运行即可。。。。。。。。。。。。。。。。