vue脚手架配置代理

1,318 阅读1分钟

1.1 作用

解决跨域问题:通过Vue-CLI里的proxy

2.1 使用

在根目录在的vue.config.js文件下配置 (注意:每次修改此文件都需要重新启动项目)

2.1.1 方式一

devServer:{
  proxy:"http://localhost:5000"     //后端提供的地址
}
//优点:配置简单
//缺点:不能配合多个代理,不能控制是否走代理

2.2.2 方式二

module.exports = {
    devServer: {
      proxy: {
      '/api1': {    // 匹配所有以 '/api1'开头的请求路径
        target: 'http://localhost:5000',    //后端提供的地址
        changeOrigin: true, //用于控制请求头中的host值
        pathRewrite: {'^/api1': ''} //在向后端发送请求时去掉api1,具体加不加看后端给的地址
      },
      '/api2': {
        target: 'http://localhost:5001',
        changeOrigin: true,
        pathRewrite: {'^/api2': ''}
      }
    }
  }
}
//1. 优点:可以配置多个代理,且可以灵活的控制请求是否走代理。
//2. 缺点:配置略微繁琐,请求资源时必须加前缀。

3.1 案例

vue.config.js

//我们假设后端提供的地址为 http://localhost:5000/list
module.exports = {
    devServer: {
      proxy: {
      '/api1': {    
        target: 'http://localhost:5000',    
        changeOrigin: true,
        pathRewrite: {'^/api1': ''} 
      }
    }
  }
}

xxx.vue

//简单的使用axios发送请求,因为配置好了代理 我们直接访问http://localhost:8080/api1/list就可以了
axios.get('http://localhost:8080/api1/list')    
    .then(
        (res)=>{}
    )
    .catch(
        (err)=>{}
    )

如果觉得有帮助欢迎点赞、评论。 上述内容仅仅代表个人观点,如有错误,请指正。如果你也对前端感兴趣,欢迎访问我的个人博客sundestiny.github.io/myblog/