当前位置:   article > 正文

axios get post all 请求 数据 // axios数据请求拦截 //axios封装_axios 响应拦截器怎么知道接口是 get 请求

axios 响应拦截器怎么知道接口是 get 请求

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 

代码  

  1. <template>
  2. <div>
  3. <button @click="getData">获取数据</button>
  4. </div>
  5. </template>
  6. <script>
  7. import axios from 'axios';
  8. export default {
  9. methods: {
  10. getData() {
  11. // get 正常接口数据请求
  12. axios.get("https://jsonplaceholder.typicode.com/posts/55") //路径换成真的
  13. .then(response => { //监听返回
  14. console.log(response.data, 'get 正常接口数据请求');
  15. })
  16. .catch(error => {
  17. console.log(error, '失败');
  18. });
  19. // get 携带数据请求
  20. axios.get('https://jsonplaceholder.typicode.com/comments/4', {
  21. params: { // 携带数据
  22. name: 'wendy',
  23. age: 18
  24. },
  25. timeout: 3000, // 单个请求配置的超时时间
  26. })
  27. .then((res) => {
  28. console.log(res.data, 'get 携带数据请求 ')
  29. });
  30. // -------------------------------------------------------------------------------------
  31. // post 正常接口数据请求
  32. axios.post('https://jsonplaceholder.typicode.com/albums?userId=4') //路径换成真的
  33. .then(response => { //监听返回
  34. console.log(response.data, 'post 正常接口数据请求');
  35. })
  36. .catch(error => {
  37. console.log(error, '失败');
  38. });
  39. // post 携带数据请求
  40. axios.post('https://jsonplaceholder.typicode.com/albums?userId=4', {
  41. data: {
  42. name: 'why',
  43. age: 12332328
  44. }
  45. })
  46. .then((res) => {
  47. console.log(res.data,'post 携带数据请求 ')
  48. });
  49. // -------------------------------------------------------------------------------------
  50. // axios 统一请求
  51. axios.all([
  52. axios.get('https://jsonplaceholder.typicode.com/albums?userId=4'),
  53. axios.post('https://jsonplaceholder.typicode.com/todos?userId=4')
  54. ])
  55. .then((res) => {
  56. // 返回的res是个response的数组
  57. console.log(res[0].data,' axios 统一请求 ')
  58. console.log(res[1].data ,' axios 统一请求 ')
  59. })
  60. // axios 统一请求 携带数据请求
  61. axios.all([
  62. axios.get('https://jsonplaceholder.typicode.com/albums?userId=4', { params: { name: 'why', age: 18 } }),
  63. axios.post('https://jsonplaceholder.typicode.com/todos?userId=4', { params: { name: 'why', age: 18 } }),
  64. ])
  65. .then((res) => {
  66. // 返回的res是个response的数组
  67. console.log(res[0].data ,'axios 统一请求 携带数据请求')
  68. console.log(res[1].data ,'axios 统一请求 携带数据请求')
  69. })
  70. }
  71. }
  72. }
  73. </script>

假数据

(32条消息) jsonplaceholder——免费的HTTP请求假数据接口(前端小伙伴值得了解一下)_人间小美味695的博客-CSDN博客icon-default.png?t=N7T8https://blog.csdn.net/cainiaoyihao_/article/details/116599014

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

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

  1. import Vue from 'vue';
  2. import ElementUI from 'element-ui';
  3. import 'element-ui/lib/theme-chalk/index.css';
  4. import App from './App.vue';
  5. import echarts from 'echarts' //引入echarts
  6. import axios from 'axios'//引入
  7. Vue.prototype.$http = axios //正确的使用
  8. Vue.use(ElementUI);
  9. new Vue({
  10. el: '#app',
  11. echarts,
  12. render: h => h(App)
  13. });

代码

  1. <template>
  2. <div>
  3. <button @click="getData">获取数据</button>
  4. </div>
  5. </template>
  6. <script>
  7. import axios from 'axios';
  8. export default {
  9. methods: {
  10. getData() {
  11. // //2.1 请求拦截器
  12. // axios.interceptors.request.use(
  13. // function (config) {
  14. // //在请求之前做些什么
  15. // return config
  16. // },
  17. // function (error) {
  18. // //对请求错误做些什么
  19. // return Promise.reject(error)
  20. // }
  21. // )
  22. // //2.2 响应拦截器
  23. // axios.interceptors.response.use(
  24. // function (response) {
  25. // //对响应数据做点什么
  26. // return response
  27. // },
  28. // function (error) {
  29. // //对响应错误做点什么
  30. // return Promise.reject(error)
  31. // }
  32. // )
  33. //----------------------------------------------------------------
  34. // 设置请求拦截器 config 配置对象 获取 然后进行判断 或者修改
  35. axios.interceptors.request.use(function one(config) { //请求拦截 数据
  36. console.log('请求拦截器 成功 - 1号'); //成功输出
  37. // if (this.name === 'a') { // 请求拦截 判断错误 输出 可以在这进行需要的捕获拦截
  38. // console.log('请求拦截器 成功 - 1号');
  39. // }
  40. return config; //返回
  41. }, function one(error) {
  42. console.log('请求拦截器 失败 - 1号');
  43. return Promise.reject(error); // axios 返回的是 promise数据
  44. });
  45. // 设置响应拦截器
  46. axios.interceptors.response.use(function (response) { //响应拦截器数据
  47. console.log('响应拦截器 成功 1号'); //成功响应
  48. return response; //返回
  49. }, function (error) {
  50. if (error.response.status === 401) {
  51. console.log('401错误')
  52. } else {
  53. return Promise.reject(error)
  54. }
  55. });
  56. //发送请求
  57. axios({
  58. method: 'GET',
  59. url: "https://jsonplaceholder.typicode.com/posts/55"
  60. }).then(response => {
  61. console.log(response, '成功了');
  62. });
  63. }
  64. }
  65. }
  66. </script>

 

转载

(33条消息) axios拦截器的原理及应用_axios的原理及作用_牛小小小婷~的博客-CSDN博客icon-default.png?t=N7T8https://blog.csdn.net/hannah2233/article/details/126646242
(33条消息) axios 中使用请求响应拦截器_axios响应拦截器_旧梦星轨的博客-CSDN博客icon-default.png?t=N7T8https://blog.csdn.net/qq_60961397/article/details/129839263

Vue.js axios响应拦截如何获取返回状态码_vue.js_脚本之家 (jb51.net)icon-default.png?t=N7T8https://www.jb51.net/article/273205.htm

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

axios 封装

index.vue

  1. <template>
  2. <div>
  3. <button @click="getData">获取数据</button>
  4. </div>
  5. </template>
  6. <script>
  7. // 引入 http 这个是request 暴露出来的
  8. import http from '../components/request'
  9. export default {
  10. methods: {
  11. getData() {
  12. // 请求 路径 监听
  13. http.post("https://jsonplaceholder.typicode.com/comments").then(r => {
  14. console.log(r, 'asasasa') //至于为啥子 undefined 我也不知道 没搞清楚
  15. })
  16. http.get("https://jsonplaceholder.typicode.com/todos?userId=4").then(r => {
  17. console.log(r, 'asasasa')
  18. })
  19. // 请求 路径 监听 携带数据
  20. http.get("https://jsonplaceholder.typicode.com/comments", {
  21. firstName: 'Fre撒旦水水水水水水水水水水水水水水d',
  22. lastName: 'Flintstone'
  23. })
  24. .then(function (response) {
  25. console.log(response,'asa');
  26. })
  27. }
  28. }
  29. }
  30. </script>

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

  1. import Vue from 'vue';
  2. import ElementUI from 'element-ui';
  3. import 'element-ui/lib/theme-chalk/index.css';
  4. import App from './App.vue';
  5. import echarts from 'echarts' //引入echarts
  6. import http from './components/request'
  7. Vue.prototype.http = http
  8. import axios from 'axios'//引入
  9. Vue.prototype.http = axios //正确的使用
  10. Vue.use(ElementUI);
  11. new Vue({
  12. el: '#app',
  13. echarts,
  14. render: h => h(App)
  15. });

request.js

  1. import axios from "axios";
  2. //1.允许创建axios实例
  3. const instance = axios.create({
  4. baseURL: "http://jsonplaceholder.typicode.com/",
  5. // 表示超时事件 如果超过这个时间 就不再请求 进行报错
  6. // Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'data')
  7. timeout: 5000000,
  8. //请求头
  9. headers: { "Content-Type": "application/json " },
  10. //会在原先传的参数的情况下 前面添加一项 可以用于传token
  11. // get请求使用
  12. params: {
  13. token: localStorage.getItem("token"),
  14. },
  15. // post请求使用
  16. data: {
  17. token: localStorage.getItem("token"),
  18. },
  19. });
  20. // 2.拦截器
  21. // 请求拦截器
  22. // 在发送请求之前执行这个函数
  23. instance.interceptors.request.use(
  24. function (config) {
  25. // 参数config是要发送给后端的所有内容
  26. // 在发送请求之前统一做一些事情 比如发送token 更换请求头
  27. // console.log(config);
  28. // 如果是上传文件的请求 更改请求头
  29. // if (config.url === "/file/upload") {
  30. // config.headers = ...
  31. // }
  32. return config;
  33. },
  34. (error) => {
  35. // 对请求错误做些什么
  36. return Promise.reject(error);
  37. }
  38. );
  39. // 响应拦截器
  40. // 在刚好接收数据的时候执行
  41. instance.interceptors.response.use(
  42. function (response) {
  43. console.log(response); //数据对象
  44. // 对响应数据做点什么
  45. //? 可以在这里过滤数据 要哪个数据返回哪个数据
  46. //? 可以在这处理状态码
  47. if (response.status === 200) {
  48. return response; //这里return出去的东西是returnget或者post方法的.then方法里
  49. } else if (response.status === 500) {
  50. // 抛错导catch
  51. // 这里404错误无法处理
  52. throw new Error("505 服务器端错误...");
  53. }
  54. },
  55. function (error) {
  56. // 对响应错误做点什么
  57. return Promise.reject(error);
  58. }
  59. );
  60. const http = {
  61. // 参数可以直接传递 params直接是对象
  62. get(url, params) {
  63. //使用实例请求 可以直接自动拼接baseURL
  64. return instance
  65. .get(url, {
  66. params: params,
  67. })
  68. .then((res) => {
  69. if (res.data.status === 0) {
  70. return res;
  71. }
  72. })
  73. .catch((err) => {
  74. // 捕获错误信息 timeout of 1000ms exceeded 捕获之后可以将这个换成轻提示
  75. // console.log(err.message);
  76. if (err.message === "timeout of 1000ms exceeded") {
  77. alert("请求超时");
  78. }
  79. alert("服务器端错误");
  80. });
  81. },
  82. post(url, data) {
  83. return instance
  84. .post(url, data)
  85. .then((response) => {
  86. return response;
  87. })
  88. .catch((error) => {
  89. console.log(error);
  90. });
  91. },
  92. };
  93. export default http;

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

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

找到这个文件:

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

 

(34条消息) 封装 axios 详解_axios封装_睡醒敲代码的博客-CSDN博客icon-default.png?t=N7T8https://blog.csdn.net/weixin_68589742/article/details/125810996

(34条消息) 总结一下axios的封装方法_axios封装_RyanKao2001的博客-CSDN博客icon-default.png?t=N7T8https://blog.csdn.net/gaowencheng01/article/details/122969385

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/148078
推荐阅读
相关标签
  

闽ICP备14008679号