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

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

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

推荐文章

IP地址获取函数
2024-11-19 00:03:29 +0800 CST
手机导航效果
2024-11-19 07:53:16 +0800 CST
一个简单的打字机效果的实现
2024-11-19 04:47:27 +0800 CST
PHP 微信红包算法
2024-11-17 22:45:34 +0800 CST
php腾讯云发送短信
2024-11-18 13:50:11 +0800 CST
CSS 实现金额数字滚动效果
2024-11-19 09:17:15 +0800 CST
php内置函数除法取整和取余数
2024-11-19 10:11:51 +0800 CST
go命令行
2024-11-18 18:17:47 +0800 CST
百度开源压测工具 dperf
2024-11-18 16:50:58 +0800 CST
JavaScript 的模板字符串
2024-11-18 22:44:09 +0800 CST
Go 单元测试
2024-11-18 19:21:56 +0800 CST
MySQL设置和开启慢查询
2024-11-19 03:09:43 +0800 CST
Vue3中哪些API被废弃了?
2024-11-17 04:17:22 +0800 CST
如何在Rust中使用UUID?
2024-11-19 06:10:59 +0800 CST
15 个你应该了解的有用 CSS 属性
2024-11-18 15:24:50 +0800 CST
程序员茄子在线接单