喵星之旅-狂奔的兔子-vue跨域解决

这里的vue项目是vue create命令创建的。

一、安装axios

(可以参考http://www.axios-js.com/docs/vue-axios.html

在项目中执行

npm install --save axios vue-axios

二、在main.js中添加

import Vue from 'vue'
import axios from 'axios'
import VueAxios from 'vue-axios'

Vue.use(VueAxios, axios)

三、修改配置文件

位于项目根路径下的vue.config.js,与src同级,如果没有则添加。

添加如下配置:

module.exports = {
    devServer: {
        //以上的ip和端口是我们本机的;下面为需要跨域的
        proxy: {//配置跨域
            '/api': {
                target: 'http://127.0.0.1:8111/',//这里后台的地址模拟的;应该填写你们真实的后台接口
                ws: true,
                changOrigin: true,//允许跨域
                pathRewrite: {
                    '^/api': ''//请求的时候使用这个api就可以
                }
            }
            
        }
    }
}

四、方法中使用

(可以参考http://www.axios-js.com/docs/vue-axios.html

    this.axios.get("/api/test/hello").then((response) => {
        this.menuList = response.data;
        
    })

这里面访问的真实地址就是 http://127.0.0.1:8111/test/hello

 

或者post请求:

 this.axios.post(`/api/test/login`,"username=" + this.loginForm.username + "&password=" + this.loginForm.password)
            .then(res=>{
                console.log('res=>',res);      
                 console.log(res.data); 
                 
            })

 

 

 

 

posted @ 2020-11-11 15:07  喵星兔  阅读(127)  评论(0编辑  收藏  举报