美文网首页
vue跨域访问后台api

vue跨域访问后台api

作者: heliping_peter | 来源:发表于2020-02-06 15:07 被阅读0次

    1.设置代理
    后台为本机端口9090,所以代理为本机端口9090,url以api开头,并访问后台时去掉api
    vue.config.js

    module.exports = {
        publicPath: '/',
        outputDir: 'dist',
        devServer: {
          open: true,
          host: 'localhost',
          port: '8081',
          proxy: {
            '/api': {
              target: 'http://localhost:9090', // 要请求的地址
              ws: true,
              changeOrigin: true,
              pathRewrite: {
                '^/api': ''
              }
            }
          }
        }
      };
    

    2.设置入口
    main引入axios,并且将axios设置为vue的特性

    import Vue from 'vue'
    import App from './App.vue'
    import router from '@/router'
    import axios from 'axios'
     
    Vue.config.productionTip = false
    Vue.prototype.$axios = axios
    new Vue({
     
      router,
      render: h => h(App),
    }).$mount('#app')
    

    3.使用api访问后台
    后台使用axios,后台的url前面需要加api,实现跨域

    <template>
      <div class="hello">
        <h1>{{ msg }}</h1>
        <p>
          gogogo,{{ msg }}
         
        </p>
    
       
      </div>
    </template>
    
    <script>
    
    export default {
      name: 'Abc',
      data() {
        return {
          msg: ''
        }
        
      },
      created() {
            this.$axios.get('/api/home').then(result=>{            
                this.msg = result.data;
            })
        }
    }
    
    
    
    </script>
    
    <!-- Add "scoped" attribute to limit CSS to this component only -->
    <style scoped>
    h3 {
      margin: 40px 0 0;
    }
    ul {
      list-style-type: none;
      padding: 0;
    }
    li {
      display: inline-block;
      margin: 0 10px;
    }
    a {
      color: #42b983;
    }
    </style>
    

    相关文章

      网友评论

          本文标题:vue跨域访问后台api

          本文链接:https://www.haomeiwen.com/subject/hcquxhtx.html