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

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

#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请求

推荐文章

【SQL注入】关于GORM的SQL注入问题
2024-11-19 06:54:57 +0800 CST
css模拟了MacBook的外观
2024-11-18 14:07:40 +0800 CST
一个数字时钟的HTML
2024-11-19 07:46:53 +0800 CST
如何在 Vue 3 中使用 TypeScript?
2024-11-18 22:30:18 +0800 CST
MySQL数据库的36条军规
2024-11-18 16:46:25 +0800 CST
总结出30个代码前端代码规范
2024-11-19 07:59:43 +0800 CST
Golang 中你应该知道的 noCopy 策略
2024-11-19 05:40:53 +0800 CST
从Go开发者的视角看Rust
2024-11-18 11:49:49 +0800 CST
jQuery中向DOM添加元素的多种方法
2024-11-18 23:19:46 +0800 CST
15 个你应该了解的有用 CSS 属性
2024-11-18 15:24:50 +0800 CST
api远程把word文件转换为pdf
2024-11-19 03:48:33 +0800 CST
WebSocket在消息推送中的应用代码
2024-11-18 21:46:05 +0800 CST
纯CSS绘制iPhoneX的外观
2024-11-19 06:39:43 +0800 CST
2025,重新认识 HTML!
2025-02-07 14:40:00 +0800 CST
如何在Vue3中定义一个组件?
2024-11-17 04:15:09 +0800 CST
deepcopy一个Go语言的深拷贝工具库
2024-11-18 18:17:40 +0800 CST
程序员茄子在线接单