当前位置:   article > 正文

axios 网络请求和代理服务器_vue3的axios配置baseurl默认指向了本地,没走代理

vue3的axios配置baseurl默认指向了本地,没走代理
  • Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。
  • http://www.axios-js.com/zh-cn/docs/
  • http(s): //httpbin.org/
    这个网站专门是为了给http做测试用的,支持各种http/s的接口.

(一)基本使用

axios配置: https://blog.csdn.net/itkingone/article/details/81083597

  1. 安装axios
    进入到项目根目录

    npm install axios --save
    
    • 1
  2. 在vue项目中引入axios:
    在需要使用axios的.vue页面(如:App.vue)中引入axios,根据需求进行使用

    //引入axios
    import axios from "axios";
    
    export default {
      name: "App",
      mounted() { //在组件加载完成后发送请求
        axios({ 
        	//如果vue运行的地址是http://127.0.0.1:80,则http://127.0.0.1:80可以省略
          url: "http://127.0.0.1:80/home/student", //请求的资源
          method: "get",  //发送get请求
          params: {  //请求所需数据
            name: "shoe",
            page: 1,
          },
        })
          .then(function (res) {
            console.log(res.data); //真正的数据在res.data中
          })
          .catch(function (err) {
            console.log("请求失败:" + err);
          });
      },
    };
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
  3. 发送多个请求,并且在所有请求完成后再处理

    axios.all([axios({
      url: "http://127.0.0.1:80/home/multidata"
    }), axios({
      url: "http://127.0.0.1:80/home/data",
      params: {
        type: 'sell',
        page: 5
      }
    })]).then(results => console.log(results));
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

(二) 代理服务器与跨域请求

  • 参考文档:https://cli.vuejs.org/zh/config/#devserver
  • 如果你的前端应用和后端 API 服务器没有运行在同一个主机上,你需要在开发环境下将 API 请求代理到 API 服务器。

[1]. 请求单个跨域服务器的资源

  • 注意下边的配置:只有在本地不存在请求的资源时才会将请求转发给服务器(有限匹配本地资源)
  1. 配置自己的代理服务器(所有本地没有的资源,都会请求一次远程服务器)
    在vue.config.js(如果根目录下没有该文件,则自己创建)里添加如下配置:

    //如果vue.config.js文件中已经存在module.exports,
    //只需将devSever的内容粘贴进已存在的module.exports的里边即可
    module.exports = {  
      devServer: {
        proxy: 'http://localhost:4000'  //配置自己的服务器地址
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
  2. vue请求代理服务器,让代理服务器去真正的服务器请求数据

    在组件中发送请求(如App.vue文件中)

    import axios from "axios";
    
    export default {
      name: "App",
      mounted() {
        axios({
          //下边的url是 http://localhost:8080/student 的缩写
          //其中http://localhost:8080是你的vue所运行的地址
          //代理服务器实际请求的地址是http://localhost:4000/student
          //http://localhost:4000 是你在vue.config.js配置的服务器的地址
          url: "/student", 
          method: "get",
          params: {
            name: "shoe",
            page: 1,
          },
        })
          .then(function (res) {
            console.log(res.data); //真正的数据在res.data中
          })
          .catch(function (err) {
            console.log("请求失败:" + err);
          });
      },
    };
    
    • 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

[2]. 请求多个跨域服务器的资源

  1. 在 .vue文件中引入axios (如:App.vue)

    <template>
      <div id="app">
        <button @click="getStudentsInfo">获取学生信息</button>
        <button @click="getCarsInfo">获取汽车信息</button>
      </div>
    </template>
    
    <script>
    import axios from "axios";
    
    export default {
      name: "App",
      methods: {
        getStudentsInfo() {
          axios({
           //下边的url是 http://localhost:8080/peaple/students 的缩写
          //其中http://localhost:8080是你的vue所运行的地址
          //代理服务器实际请求的地址是http://localhost:5000/student
            url: "/peaple/students",
            method: "get",
            params: {
              name: "shoe",
            },
          })
            .then(function (res) {
              console.log(res.data); //真正的数据在res.data中
            })
            .catch(function (err) {
              console.log("请求失败:" + err);
            });
        },
        getCarsInfo() {
          axios({
          	//代理服务器实际请求的地址是http://localhost:5001/cars
            url: "/tool/cars",
            method: "get",
            params: {
              name: "shoe",
            },
          })
            .then(function (res) {
              console.log(res.data); //真正的数据在res.data中
            })
            .catch(function (err) {
              console.log("请求失败:" + err);
            });
        },
      },
    };
    </script>
    
    • 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
    • 50
  2. 在根目录下的vue.config.js(如果没有该文件,则需自己创建)开始配置代理服务器

    配置中的 pathRewrite,将请求地址的某些字段通过正则匹配替换掉(如:pathRewrite:{’^/peaple’:’’},表示将请求地址中以/peaple开头的字段,替换成空字符串,如‘http://localhost:8080/peaple/students’,经过代理服务器之后得请求地址为:‘http://localhost:5000/students’)

    module.exports = {
      devServer: {
        proxy: {
          '/peaple': {  //匹配所有以"/peaple"开头的请求路径(App.vue获取学生信息的的请求将走该路径)
            target: 'http://localhost:5000', //代理目标的基础路径
            pathRewrite:{'^/peaple':''},//将请求地址中的/peaple替换为空字符串,如果请求的地址需要/peple也可以不设置
            ws: true,//websocket 默认为true
            changeOrigin: true  //是否修改请求头中的host与请求的目标地址一致(本例为将请求头的host改为:http://localhost:5000) 默认为true
          },
          '/tool': {//匹配所有以"/tool"开头的请求路径(App.vue获取汽车信息的的请求将走该路径)
            target: 'http://localhost:5001',
            pathRewrite:{'^/tool':''},  //将请求地址中的/tool替换为空字符串
          }
        }
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

(三) axios实例

如果不希望一个axios使用默认的axios配置,而是单独使用自己的配置时,需要创建axios实例。
每个实例都可以有自己的配置,相互不干扰

//创建axios实例
const instance1 = axios.create({
  baseURL:'http://127.0.0.1:80',
  timeout: 5000
});

//发送请求
instance1({
  url:"/home/multidata",
  params: {
    type:'sell',
    page: 1
  }
}).then(res => console.log(res));
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

(四) axios封装

当vue组件中有多个文件同时需要引入axios时,需要封装起来,让组件来引入封装的文件,避免因需要更换axios而需要修改多个文件。

  1. 创建单独的文件/src/netwrk/request.js

    import axios from "axios";
    
    export function request1(config){
        // 1. 创建axios实例
        const instance = axios.create({
            baseURL:'127.0.0.1:80',
            timeout: 5000
        });
        
        // 2.发送真正的网络请求,返回一个promise
        return instance(config);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
  2. 在组件中引入

    import {request1} from "./network/request";
    
    request1({
      url:"/home/multidata",
      params: {
        type:'sell',
        page: 1
      }
    }).then(success=>console.log(success)).catch(err=>console.log(err));
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

(五) axios拦截器

axios提供了拦截器,用于我们在发送每次请求或者得到响应后,进行对应的处理
在请求或响应被 then 或 catch 处理前拦截它们。

在/src/netwrk/request.js中

import axios from "axios";

export function request1(config){
    // 1. 创建axios实例
    const instance = axios.create({
        baseURL:'http://127.0.0.1:80',
        timeout: 5000
    });
    // 2. 进行拦截和处理
    // 添加请求拦截器
    instance.interceptors.request.use(function (config) {
        // 在发送请求之前做些什么
        console.log("对网址请求成功!");
        //对响应的数据进行处理
        console.log(config);
        //请求成功(必须返回)
        return config;
    }, function (error) {
        // 对请求错误做些什么
        console.log("对网址请求失败!");

        return Promise.reject(error);
    });

    // 添加响应拦截器
    instance.interceptors.response.use(function (response) {
        // 对响应数据做点什么
        console.log("网址响应成功!");
        //对响应的数据进行处理
        console.log(response);
        
        return response;
    }, function (error) {
        // 对响应错误做点什么
        console.log("网址响应失败!");
        return Promise.reject(error);
    });
    
    // 3.发送真正的网络请求
    return instance(config);
}
  • 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
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/459202
推荐阅读