vue-cli项目使用webpack的proxy设置代理,调用yapi模拟数据

2,000 阅读2分钟

假设在开发的时候,后端接口还没有做好,那么我们有可能会用到模拟接口(比如利用yapi),那么当我们在用模拟接口的时候(开发时候有两个后端域名),可以用两种方式来解决.第一是通过代理=proxy,第二直接通过axios判断.

接口均来自于网络:

开发域名: poetry.apiopen.top + /sentences
mock域名:http://47.110.148.106:3030/mock/11 + /search/search_record

1.axios有请求拦截

request.js文件

const baseURL = 'http://poetry.apiopen.top'
const service = axios.create({
  baseURL: baseURL,
  timeout: 100000 // request timeout
})
service.interceptors.request.use(
  config => {
    if (config.url.indexOf('mock_data') > -1) {
      config.baseURL = 'http://47.110.148.106:3030/mock/11/'
      config.url = config.url.substring(6)
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

当我们请求开发域名时候:

export function getRankList() {
  return request({
    url: '/sentences',
    method: 'get',
  })
}

mock域名的时候:

export function getRankList() {
  return request({
    url: '/mock_data/search/search_record',
    method: 'get',
  })
}

通过一个/mock来进行区分.

2.proxy拦截

1 .env.development文件中定义基础的接口名(开发接口标志):

VUE_APP_BASE_API = '/api_data'

那么每个页面都可以通过process.env.VUE_APP_BASE_API获取到

2 request.js中定义haseUrl

const baseURL = process.env.VUE_APP_BASE_API
const service = axios.create({
  baseURL: baseURL,
  timeout: 100000 // request timeout
})

service.interceptors.request.use(
  config => {
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

3 vue.config.js中拦截

module.exports = {
  devServer: {
    host: 'localhost',
    port: 8080,
    open: true,// vue项目启动时自动打开浏览器
    https: false,
    proxy: {
      '/api_data/mock_data/': {
        target: 'http://47.110.148.106:3030/mock/11',
        changeOrigin: true,
        pathRewrite: { '^/api_data/mock_data/': '' },
      },
      '/api_data': {
        target: 'http://poetry.apiopen.top',
        changeOrigin: true,
        pathRewrite: { '^/api_data': '' },
        
      },
    },
  }
}


// '^/api_data'是一个正则表达式,
// 表示要匹配请求的url中,全部'http://poetry.apiopen.top/api_data' 转接为http://poetry.apiopen.top

4 测试

模式数据:

export function getRankList() {
  return request({
    url: '/mock_data/search/search_record',
    method: 'get',
  })
}

开发数据:

export function getRankList() {
  return request({
    url: '/sentences',
    method: 'get',
  })
}

3.两种方式有什么区别

我们采用的第二种,或许你们有更好的方法,因为proxy代理能够解决跨域的问题,请求服务端的接口一般是会由服务端去解决跨域的问题,请求其他的接口,前端也应该尽可能的避免跨域!

还有每次修改完vue.config.js,一定要再次运行一下!!!

4.参考

vue-cli模式与环境配置
devServer.proxy

5.我的公众号

最近在写一些关于在前端行业摸爬滚打还有生活中的趣事来让自己变得更加快乐,追求生活和工作中的进步

c79fa8967887df6527a162bd85cae3a.jpg