若依框架 用axios请求接口的使用以及配置

若依框架前后端分离 用axios请求接口的使用以及配置

首先需要下载安装

cnpm install axios --save

安装完成以后进行配置,打开main.js

import axios from 'axios'
Vue.prototype.$axios = axios    //全局注册,使用方法为:this.$axios

跨域配置:
打开vue.config.js

在这里插入图片描述
可以看到一个案例,这个就是跨域请求的写法我们只需要模仿人家写好的就可以

'/api': {
        target: 'http://xxxx.xxx.xx.xxx:xxxx/',//设置你调用的接口域名和端口号
        changeOrigin: true, //跨域这个必须是true因为是跨域
        pathRewrite: {
          '^/api': '/' //这里理解成用‘/api’代替target里面的地址,
          //后面组件中我们调接口时直接用api代替
          //比如我要调用
          //'http://xxxx.xxx.xx.xxx:xxxx/xxx/aaa?a=1',
          //直接写‘/api/xxx/aaa?a=1’即可
        }
      }

完成了以上的配置就可以在vue页面进行请求接口了

this.$axios({
          method: 'post',
          url: '/api/xxxx/xx',
          data:{
          	字段名:'值'}
        }).then((response) =>{    
         alert(JSON.stringify(response));//请求成功返回的数据
        }).catch((error) =>{   
          alert(error);   //请求失败返回的数据
        })
发布了34 篇原创文章 · 获赞 5 · 访问量 2252

猜你喜欢

转载自blog.csdn.net/tanfei_/article/details/103751161