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

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

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

推荐文章

Gin 与 Layui 分页 HTML 生成工具
2024-11-19 09:20:21 +0800 CST
Flet 构建跨平台应用的 Python 框架
2025-03-21 08:40:53 +0800 CST
Vue3结合Driver.js实现新手指引功能
2024-11-19 08:46:50 +0800 CST
JS中 `sleep` 方法的实现
2024-11-19 08:10:32 +0800 CST
使用Python实现邮件自动化
2024-11-18 20:18:14 +0800 CST
避免 Go 语言中的接口污染
2024-11-19 05:20:53 +0800 CST
平面设计常用尺寸
2024-11-19 02:20:22 +0800 CST
PHP openssl 生成公私钥匙
2024-11-17 05:00:37 +0800 CST
2024年公司官方网站建设费用解析
2024-11-18 20:21:19 +0800 CST
imap_open绕过exec禁用的脚本
2024-11-17 05:01:58 +0800 CST
什么是Vue实例(Vue Instance)?
2024-11-19 06:04:20 +0800 CST
快速提升Vue3开发者的效率和界面
2025-05-11 23:37:03 +0800 CST
Vue3中如何处理WebSocket通信?
2024-11-19 09:50:58 +0800 CST
js生成器函数
2024-11-18 15:21:08 +0800 CST
Vue3中的Scoped Slots有什么改变?
2024-11-17 13:50:01 +0800 CST
10个极其有用的前端库
2024-11-19 09:41:20 +0800 CST
为什么大厂也无法避免写出Bug?
2024-11-19 10:03:23 +0800 CST
php指定版本安装php扩展
2024-11-19 04:10:55 +0800 CST
Python 获取网络时间和本地时间
2024-11-18 21:53:35 +0800 CST
程序员茄子在线接单