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

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

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

推荐文章

开发外贸客户的推荐网站
2024-11-17 04:44:05 +0800 CST
免费常用API接口分享
2024-11-19 09:25:07 +0800 CST
Node.js中接入微信支付
2024-11-19 06:28:31 +0800 CST
markdowns滚动事件
2024-11-19 10:07:32 +0800 CST
Vue3结合Driver.js实现新手指引功能
2024-11-19 08:46:50 +0800 CST
thinkphp分页扩展
2024-11-18 10:18:09 +0800 CST
PyMySQL - Python中非常有用的库
2024-11-18 14:43:28 +0800 CST
关于 `nohup` 和 `&` 的使用说明
2024-11-19 08:49:44 +0800 CST
php指定版本安装php扩展
2024-11-19 04:10:55 +0800 CST
gin整合go-assets进行打包模版文件
2024-11-18 09:48:51 +0800 CST
linux设置开机自启动
2024-11-17 05:09:12 +0800 CST
用 Rust 玩转 Google Sheets API
2024-11-19 02:36:20 +0800 CST
向满屏的 Import 语句说再见!
2024-11-18 12:20:51 +0800 CST
mysql int bigint 自增索引范围
2024-11-18 07:29:12 +0800 CST
Redis函数在PHP中的使用方法
2024-11-19 04:42:21 +0800 CST
使用Ollama部署本地大模型
2024-11-19 10:00:55 +0800 CST
html夫妻约定
2024-11-19 01:24:21 +0800 CST
ElasticSearch集群搭建指南
2024-11-19 02:31:21 +0800 CST
前端如何一次性渲染十万条数据?
2024-11-19 05:08:27 +0800 CST
Vue 3 中的 Watch 实现及最佳实践
2024-11-18 22:18:40 +0800 CST
Vue3中的组件通信方式有哪些?
2024-11-17 04:17:57 +0800 CST
程序员茄子在线接单