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

2024-11-19 03:04:20 +0800 CST views 3596

#1. 开发环境跨域配置
在 vue.config.js 文件中:

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

注意,配置完成后要重启服务
配置 axios 请求的 baseUrl
http.js文件中配置

axios.defaults.timeout = 5000 // 请求超时
axios.defaults.baseURL = '/api/';

页面中发送请求:

this.$ajax.get('/api/index?page='+this.page)
      .then(function(res) {
        console.log(res);
      });

此时,虽然发送的请求到地址:http://127.0.0.10:8071/api/index?page=1, 但是已经代理到了地址: http://1.b.cn:88/api/index?page=1
0.png
2. 生产环境 api 请求接口 baseUrl 配置

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

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

this.$ajax.get('/api/index?page='+this.page)
      .then(function(res) {
        console.log(res);
      });

实际请求地址为:http://api.com/api/index?page=1

效果图
2.png

复制全文 生成海报 Vue.js 前端开发 API请求

推荐文章

介绍25个常用的正则表达式
2024-11-18 12:43:00 +0800 CST
2024年微信小程序开发价格概览
2024-11-19 06:40:52 +0800 CST
Vue3中的Scoped Slots有什么改变?
2024-11-17 13:50:01 +0800 CST
从Go开发者的视角看Rust
2024-11-18 11:49:49 +0800 CST
如何在Rust中使用UUID?
2024-11-19 06:10:59 +0800 CST
Vue3中如何处理状态管理?
2024-11-17 07:13:45 +0800 CST
实现微信回调多域名的方法
2024-11-18 09:45:18 +0800 CST
淘宝npm镜像使用方法
2024-11-18 23:50:48 +0800 CST
Nginx 防止IP伪造,绕过IP限制
2025-01-15 09:44:42 +0800 CST
聚合支付管理系统
2025-07-23 13:33:30 +0800 CST
快速提升Vue3开发者的效率和界面
2025-05-11 23:37:03 +0800 CST
如何配置获取微信支付参数
2024-11-19 08:10:41 +0800 CST
Linux 常用进程命令介绍
2024-11-19 05:06:44 +0800 CST
api接口怎么对接
2024-11-19 09:42:47 +0800 CST
程序员茄子在线接单