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

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

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

推荐文章

Vue 中如何处理跨组件通信?
2024-11-17 15:59:54 +0800 CST
在JavaScript中实现队列
2024-11-19 01:38:36 +0800 CST
MySQL 主从同步一致性详解
2024-11-19 02:49:19 +0800 CST
详解 Nginx 的 `sub_filter` 指令
2024-11-19 02:09:49 +0800 CST
Python Invoke:强大的自动化任务库
2024-11-18 14:05:40 +0800 CST
php机器学习神经网络库
2024-11-19 09:03:47 +0800 CST
IP地址获取函数
2024-11-19 00:03:29 +0800 CST
Vue 3 路由守卫详解与实战
2024-11-17 04:39:17 +0800 CST
Vue3中如何处理状态管理?
2024-11-17 07:13:45 +0800 CST
php strpos查找字符串性能对比
2024-11-19 08:15:16 +0800 CST
阿里云免sdk发送短信代码
2025-01-01 12:22:14 +0800 CST
XSS攻击是什么?
2024-11-19 02:10:07 +0800 CST
微信小程序热更新
2024-11-18 15:08:49 +0800 CST
Hypothesis是一个强大的Python测试库
2024-11-19 04:31:30 +0800 CST
Vue3中如何实现插件?
2024-11-18 04:27:04 +0800 CST
liunx服务器监控workerman进程守护
2024-11-18 13:28:44 +0800 CST
Roop是一款免费开源的AI换脸工具
2024-11-19 08:31:01 +0800 CST
程序员茄子在线接单