vue.config.js配置

vue使用axios调用接口地址,配置一个服务端的代理,隐藏真实请求地址

1、vue.config.js配置

devServer: {
  open: true,
  port: port,
  overlay: {
    // 在浏览器不显示编译的警告
    warnings: false,
    // 在浏览器上显示编译的错误
    errors: true
  },
  proxy: {
    [process.env.VUE_APP_BASE_API]: {// 使用环境变量中的值
      target: 'http://localhost:8790/, //服务端接口地址
      changeOrigin: true,
      pathRewrite: { // 重写真实请求地址
        ['^' + process.env.VUE_APP_BASE_API]: '/'
      }
    }
  }
}

2、在.env.development中配置VUE_APP_BASE_API

VUE_APP_BASE_API = '/api/'

注意:必须使用VUE_APP开头的环境变量名称,否则读取不到

3、request.js配置

import axios from 'axios'
// 创建一个 axios 实例
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  timeout: 10000 // request timeout
})

// request interceptor请求拦截器
service.interceptors.request.use(
  config => {
    // do something before request is sent 在发出请求前
    console.log(config)
    return config
  },
  error => {
    // do something with request error 处理请求错误
    return Promise.reject(error)
  }
)

// response interceptor 响应拦截器
service.interceptors.response.use(
  response => {
    // 返回值 是失败的
    if (response.data.isSuccess !== true) {
      if (res.data.code === -1) { // 错误码是-1 时
        return retryNotErrReq(res.config)
      } else {
        handleError(res.data.code, res.data.msg)
        return Promise.reject(new Error(res.data.msg || 'Error'))
      }
    } else {
      return res
    }
  },
  error => {
     return Promise.reject(error)
  }
)

export default service

4、api.js配置

import request from './request'

export function testMessage() {
  return request({
    url: '/boardPush/testMessage',
    method: 'post'
  })
}

5、使用

testMessage().then(msg => {
  console.log(msg)
})

在这里插入图片描述

6、总结

请求地址:http://localhost:8082/api/boardPush/testMessage

真实请求地址:http://localhost:8790/boardPush/testMessage

其中将http://localhost:8082/api/ 转换成了http://localhost:8790/api/,并且重写了url地址,将其中的/api/替换成了/得到了真实的请求地址

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值