Vue学习(十八)配置代理

本文介绍了在Vue脚手架中配置代理的两种方法,包括在vue.config.js中添加代理配置及其优缺点。方法一简单但不灵活,适用于单一代理需求;方法二允许配置多个代理,但配置过程较复杂,需要添加请求前缀。

脚手架配置代理

方法一

在vue.config.js中添加如下配置

devServer:  {
    proxy: "url"
}

说明:

  • 优点:配置简单,请求资源时直接发给前端(url)即可。
  • 缺点:不能配置多个代理,不能灵活控制请求是否走代理。
  • 工作方式:当前前端中不存在资源时,请求才会转发给服务器。不然就会请求当前前端。

方法二

编写vue.config.js配置的具体规则:

module.exports = defineConfig({
  devServer: {
    proxy: {
      // 请求前缀,匹配所有以'/api'开头的请求路径
      '/api': {
        target: 'http://localhost:5000',    // 代理目标基础服务器
        pathRewrite: {'^/api': ''}, // 将发个服务器的请求,取消前缀
        ws: true, // 用于支持websocket
        changeOrigin: false  // 用于控制请求头中的host字段 默认true,如果设置为true,服务器收到的请求头的host为:localhost:5000;设置为false时,host为:localhost:当前的前端启动端口
      },
      '/carapi': {
        target: 'http://localhost:5001',
        pathRewrite: {'^/carapi': ''},
        // ws: true, // 用于支持websocket
        // changeOrigin: false  // 用于控制请求头中的host字段 默认true
      }

      /* '/foo': {
        target: '<other_url>'
      } */
    }
  }
})

说明:

  • 优点:可以配置多个代理,且可以灵活的控制请求是否走代理
  • 缺点:配置比较繁琐,请求是必须添加前缀

vue.config.js

const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,
  lintOnSave: false,  //关闭语法检查
  // 开启代理服务器,方式一: 本地public 中有的资源不会转发,只能配置一个代理
  /* devServer: {
    proxy: 'http://localhost:5000'
  } */
  devServer: {
    proxy: {
      // 请求前缀
      '/api': {
        target: 'http://localhost:5000',
        pathRewrite: {'^/api': ''},
        ws: true, // 用于支持websocket
        changeOrigin: false  // 用于控制请求头中的host字段 默认true
      },
      '/carapi': {
        target: 'http://localhost:5001',
        pathRewrite: {'^/carapi': ''},
        // ws: true, // 用于支持websocket
        // changeOrigin: false  // 用于控制请求头中的host字段 默认true
      }

      /* '/foo': {
        target: '<other_url>'
      } */
    }
  }
})

App.vue

<template>
    <div>
		<button @click="getStudents">获取学生信息</button>
		<button @click="getCars">获取汽车信息</button>
	</div>
</template>

<script>
	import axios from 'axios'
    export default {
        name: "App",
		methods: {
			getStudents() {
				axios.get('http://localhost:8080/api/student/getStudent').then(
					response => {
						console.log("请求成功了", response.data);
					},
					error => {
						console.log("请求失败了", error.message);
					}
				)
			},
			getCars() {
				axios.get('http://localhost:8080/carapi/car/getCar').then(
					response => {
						console.log("请求成功了", response.data);
					},
					error => {
						console.log("请求失败了", error.message);
					}
				)
			},
		},
    }
</script>

github请求小案例

index.html

<!DOCTYPE html>
<html lang="">
  <head>
    <meta charset="utf-8">
    <!-- 针对IE的特殊配置,让IE以最高的渲染级别渲染页面 -->
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <!-- 开启移动端的理想视口 -->
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <!-- 图标 -->
    <link rel="icon" href="<%= BASE_URL %>favicon.ico">
    <!-- 引入第三方样式 -->
    <link rel="stylesheet" href="<%= BASE_URL %>css/bootstrap.css">
    <!-- 配置网页标题 -->
    <title><%= htmlWebpackPlugin.options.title %></title>
  </head>
  <body>
    <!-- 当浏览器不支持js时,noscript中的元素就会别渲染 -->
    <noscript>
      <strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
    </noscript>
    <div id="app"></div>
    <!-- built files will be auto injected -->
  </body>
</html>

App.vue

<template>
	<div class="container">
		<Search />
		<List />
	</div>
</template>

<script>
	import Search from './components/Search.vue'
	import List from './components/List.vue'
	export default {
		name: 'App',
		components: {Search, List}
	}
</script>

Search.vue

<template>
  <section>
    <h3 class="jumbotron-heading">Search Github Users</h3>
    <div>
      <input type="text" placeholder="enter the name you search" v-model="keyWord">&nbsp;
      <button @click="searchUsers">Search</button>
    </div>
  </section>
</template>

<script>
  import axios from 'axios'
  export default {
    name: "Search",
    data() {
      return {
        keyWord: ''
      }
    },
    methods: {
      searchUsers() {
        // 请求钱更新List数据
        this.$bus.$emit('updateListData', {isFirst: false, isLoading: true, errMsg: '', users: []});
        axios.get(`https://api.github.com/search/users?q=${this.keyWord}`).then(
          response => {
            console.log("请求成功了")
            // this.$bus.$emit("updateListData", response.data.items)
            // this.$bus.$emit('updateListData', false, false, '', response.data.items);
            this.$bus.$emit('updateListData', {isLoading: false, errMsg: '', users: response.data.items});
          },
          error => {
            console.log("请求失败了", error.message)
            this.$bus.$emit('updateListData', {isLoading: true, errMsg: error.message, users: []});
          }
        )
      }
    },
  }
</script>

List.vue

<template>
  <div class="row">
    <!-- 展示用户列表 -->
    <div v-show="info.users.length" class="card" v-for="user in info.users" :key="user.login">
      <a :href="user.html_url" target="_blank">
        <img :src="user.avatar_url" style="width: 100px" />
      </a>
      <p class="card-text">{{ user.login }}</p>
    </div>
    <!-- 展示欢迎词 -->
    <h1 v-show="info.isFirst">欢迎使用!</h1>
    <!-- 展示加载中 -->
    <h1 v-show="info.isLoading">加载中....</h1>
    <!-- 展示错误信息 -->
    <h1 v-show="info.errMsg">{{ info.errMsg }}</h1>
  </div>
</template>

<script>
  export default {
    name: "List",
    data() {
      return {
        info: {
          isFirst: true,
          isLoading: false,
          errMsg: '',
          users: []
        }
      }
    },
    mounted() {
      this.$bus.$on('updateListData', (dataObj) => {
        console.log("我是list的组件,收到数据:", dataObj)
        // this.info = dataObj;
        this.info = {...this.info, ...dataObj}
        /* this.isFirst = isFirst
        this.isLoading = isLoading
        this.errMsg = errMsg
        console.log("我是list的组件,收到数据:", users)
        this.users = users; */
      })
    },
  }
</script>

<style>
  .album {
    min-height: 50rem; 
    /* Can be removed; 
    just added for demo purposes */
    padding-top: 3rem;
    padding-bottom: 3rem;
    background-color: #f7f7f7;
  }
  .card {
    float: left;
    width: 33.333%;
    padding: 0.75rem;
    margin-bottom: 2rem;
    border: 1px solid #efefef;
    text-align: center;
  }
  .card > img {
    margin-bottom: 0.75rem;
    border-radius: 100px;
  }
  .card-text {
    font-size: 85%;
  }
</style>
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值