vue-cli 3.0 axios 跨域请求代理配置及生产环境 baseUrl 配置

1. 开发环境跨域配置

在 vue.config.js 文件中:

module.exports = {
  runtimeCompiler: true,
  publicPath: '/', // 设置打包文件相对路径
  devServer: {
    // open: process.platform === 'darwin',
    // host: 'localhost',
    port: 8071,
    // open: true, //配置自动启动浏览器 
    proxy: {
      '/api': {
        target: 'http://127.0.0.1:8100/', //对应自己的接口
        changeOrigin: true,
        ws: true,
        pathRewrite: {
          '^/api': ''
        }
      }
    }
   }, 
}

注意,配置完成后要重启服务

配置 axios 请求的 baseUrl

在 main.js 中:

axios.defaults.timeout = 5000 // 请求超时
axios.defaults.baseURL = '/api/'  // api 即上面 vue.config.js 中配置的地址

页面中发送请求:

axios.post('/postData/', {
    name: 'cedric', 
}).then((res) => {
  console.log(res.data)
})

此时,虽然发送的请求到地址:http://localhost:8080/api/postData/, 但是已经代理到了地址: http://127.0.0.1:8100/postData/

2. 生产环境 api 请求接口 baseUrl 配置

只需要将 main.js 中 axios 作如下修改:

axios.defaults.timeout = 5000 // 请求超时
axios.defaults.baseURL = 'http://api.demourl.com/'

页面中 axios 请求地址的写法不变:

axios.post('/postData/', {
    name: 'cedric', 
}).then((res) => {
  console.log(res.data)
})

实际请求地址为:http://api.demourl.com/postData/

原文地址:https://www.cnblogs.com/cckui/p/10331432.html