Skip to content

29. Ajax 配置代理

29.1 Vue脚手架配置代理(axios)

本案例需要下载axiosnpm install axios

配置参考文档 Vue-Cli devServer.proxy

vue.config.js是一个可选的配置文件,如果项目的(和package.json同级的)根目录中存在这个文件,那么它会被@vue/cli-service自动加载。你也可以使用package.json中的 vue字段,但是注意这种写法需要你严格遵照JSON的格式来写

方法一

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

js
module.exports = {
  devServer:{
    proxy:"http://localhost:5000"
  }
}

说明

  1. 优点:配置简单,请求资源时直接发给前端(8080)即可

  2. 缺点:不能配置多个代理,不能灵活的控制请求是否走代理

  3. (工作方式:若按照上述配置代理,当请求了前端不存在的资源时,才会将请求会转发给服务器(优先匹配前端资源)

方法二

编写 vue.config.js 配置具体代理规则

js
module.exports = {
	devServer: {
      proxy: {
      '/api1': {							// 匹配所有以 '/api1'开头的请求路径
        target: 'http://localhost:5000',	// 代理目标的基础路径
        pathRewrite: {'^/api1':''},				// 代理往后端服务器的请求去掉 /api1 前缀
        ws: true,								// WebSocket
        changeOrigin: true,
        
      },
      '/api2': {
        target: 'http://localhost:5001',
        pathRewrite: {'^/api2': ''},
        changeOrigin: true
      }
    }
  }
}
/*
   changeOrigin设置为true时,服务器收到的请求头中的host为:localhost:5000
   changeOrigin设置为false时,服务器收到的请求头中的host为:localhost:8080
   changeOrigin默认值为true
*/

说明

  1. 优点:可以配置多个代理,且可以灵活的控制请求是否走代理
  2. 缺点:配置略微繁琐,请求资源时必须加前缀

29. 2 github 案例

index.html

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">
      
        <!-- 引入bootstrap样式 -->
        <link rel="stylesheet" href="<%= BASE_URL %>css/bootstrap.css">
      
        <!-- 配置网页标题 -->
        <title><%= htmlWebpackPlugin.options.title %></title>
    </head>
    <body>
        <!-- 容器 -->
        <div id="app"></div>
    </body>
</html>

List.vue

vue
<template>
  <div class="row">
    <div class="card" v-for="user in  info.users" :key="user.id">
      <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>
    <!-- 展示加载中 -->
    <div class="load-container" v-show="info.isLoading">
      <div class="load load1"></div>
      <div class="load load2"></div>
      <div class="load"></div>
    </div>
    <!-- 展示错误信息 -->
    <h1 v-show="info.errMsg">{{ info.errMsg }}</h1>
  </div>
</template>

<script>
export default {
  name: 'List',

  data() {
    return {
      info: {
        users: [],
        isFirst: true,
        isLoading: false,
        errMsg: ''
      }
    }
  },

  mounted() {
    this.$bus.$on('updateListData', dataObj => {
      this.info = { ...this.info, ...dataObj }
    })
  },

  methods: {}
}
</script>

<style lang="less" scoped>
.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%;
}

.load-container {
  margin: 50px auto;
  width: 150px;
  text-align: center;
  .load {
    width: 20px;
    height: 20px;
    background-color: #00adb5;

    border-radius: 100%;
    display: inline-block;
    -webkit-animation: bouncedelay 1.4s infinite ease-in-out;
    animation: bouncedelay 1.4s infinite ease-in-out;
    /* Prevent first frame from flickering when animation starts */
    -webkit-animation-fill-mode: both;
    animation-fill-mode: both;
  }
  .load1 {
    -webkit-animation-delay: -0.32s;
    animation-delay: -0.32s;
  }
  .load2 {
    -webkit-animation-delay: -0.16s;
    animation-delay: -0.16s;
  }
}

@-webkit-keyframes bouncedelay {
  0%,
  80%,
  100% {
    -webkit-transform: scale(0);
  }
  40% {
    -webkit-transform: scale(1);
  }
}

@keyframes bouncedelay {
  0%,
  80%,
  100% {
    transform: scale(0);
    -webkit-transform: scale(0);
  }
  40% {
    transform: scale(1);
    -webkit-transform: scale(1);
  }
}
</style>

Search.vue

vue
<template>
  <div>
    <section class="jumbotron">
      <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>
  </div>
</template>

<script>
import axios from 'axios'
export default {
  name: 'Search',

  data() {
    return {
      keyWord: ''
    }
  },

  mounted() {},

  methods: {
    SearchUsers() {
      this.$bus.$emit('updateListData', { isLoading: true, errMsg: '', users: [], isFirst: false })
      axios.get(`http://api.github.com/search/users?q=${this.keyWord}`).then(
        response => {
          // this.$bus.$emit('getUsers', response.data.items)
          this.$bus.$emit('updateListData', { isLoading: false, errMsg: '', users: response.data.items })
        },
        error => {
          this.$bus.$emit('updateListData', { isLoading: false, errMsg: error.message, users: [] })
        }
      )
    }
  }
}
</script>

<style lang="less" scoped>
</style>

App.vue

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

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

  data() {
    return {}
  },
  components: {
    Search,
    List
  },

  mounted() {},

  methods: {}
}
</script>

<style lang="less" scoped>
</style>

main.js

js
// 引入Vue
import Vue from 'vue'
import App from './App.vue'

// 关闭Vue的生产提示
Vue.config.productionTip = false



// 创建vm
new Vue({
  render: h => h(App),
  beforeCreate() {
	
    // 💖💖💖
    Vue.prototype.$bus = this
  }
}).$mount('#app')

29.3 vue-resource

vue项目常用的两个Ajax库

  1. axios :通用的Ajax请求库,官方推荐,效率高
  2. vue-resource : vue插件库,vue 1.x使用广泛,官方已不维护
  3. 下载 vue-resourcenpm i vue-resource

main.js

js
import Vue from 'vue'
import App from './App.vue'
// 💖💖💖
import vueResource from 'vue-resource'

Vue.config.productionTip = false

// 💖💖💖
Vue.use(vueResource)

new Vue({
    el:"#app",
    render: h => h(App),
    beforeCreate(){
        Vue.prototype.$bus = this
    }
})
js
this.$http.get(`https://api.github.com/search/users?q=${this.keyWord}`).then(
          response => {},
          error => {}

Powered by VitePress & Vue 3