Vue2.0 axios 前后端分离跨域问题 配置axios或代理(两行代码解决)

安装axios

npm install axios

代理方式

项目根目录下创建vue.config.js

在这里插入图片描述

module.exports = {
    devServer: {
        proxy: 'http://localhost:9000'
    }
}
测试代码
<template>
  <div id="app">
    <img alt="Vue logo" src="./assets/logo.png">
    <br>
    {{msg}}
  </div>
</template>

<script>

export default {
  name: 'App',
  components: {
  },
  data:()=>{
    return {
      msg:'123'
    }
  },
  async mounted() {
    console.log('发起请求')
    let res = await this.$axios.get('/examination/list?page=1&limit=10')
    console.log(res)
    this.msg = res.data
  }
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

在这里插入图片描述

配置axios baseURL方式

axios.defaults.timeout=30000
axios.defaults.baseURL='http://localhost:9000'

两种方式的区别是:
代理方式的话不会显示后端地址,仍然是走的当前IP、端口,而baseURL方式会直接显示走的配置的地址,建议使用代理配置方式。

posted @ 2021-06-14 12:03  HumorChen99  阅读(0)  评论(0编辑  收藏  举报  来源