axios FastMock 跨域 代理

发送请求:

  实现:发送请求,获取数据。

  原本想自己写服务,后来无意间找到FastMock这个东东,于是就有了下文。。。

  首先我安装了axios,在fastmock注册好了并创建了一个接口,怎么搞自行百度。

  Q&A:

  Q:怎么请求到?

  A:当然是用axios了。

  代码如下:

<script>
export default {
  name: 'HelloWorld',
  data () {
    return {
     user:''
    }
  },
   mounted () {
    console.log('加载...')
    this.$axios.post('https://www.fastmock.site/mock/e24355f6a27dfe0707757f3ea7e687d4/Ts/login'      
    ).then(function(res){
      console.log(res);
    }).catch(function(res){
      console.log(res);
    });
  }
}
</script>
View Code

跨域/代理:

  下面我们进行设置,给axios的baseURL赋值‘/api‘

axios.defaults.baseURL = '/api'

  接下来不管怎么请求,都会有xxxxx/api/xxx

  然后在config=>index.js中找到 proxyTable:{ },添加如下代码:

 proxyTable: {
        '/api': {
        target: 'https://www.fastmock.site/mock/e24355f6a27dfe0707757f3ea7e687d4/Ts',
        changeOrigin: true,
      }
    },
  •   开头的 ’/api‘ 表示当地址请求地址中存在/api/xxxx这种请求格式时将/api之前的内容换成target的值,那么还记得刚刚设置的 axios.defaults.baseURL = '/api' 吗?是不是妙哉~
  •   target:你的api地址。
  •   changeOrigin:是否可跨域。

  接下来请求直接写成 /login就行了

//使用代理地址,由于main.js中baseURL为/api,所以所有请求都会走代理地址,只要写请求方法就行
this.$axios
.post('/login',{'username':'admin','password':'123456'})
.then(response=> {console.log(response)} )
.catch(error=>console.log(error))

 

   到这请求就完成了,附上fastmock的接口(fastmock文档中的)

{
  "code": "0000",
  "data": {
    "verifySuccess": function({_req, Mock}) {
      return _req.body;
    },
    "userInfo": function({_req, Mock}) {
      let body = _req.body;
      if (body.username === 'admin' && body.password === '123456') {
        return Mock.mock({
          username: "admin",
          email: "@email",
          address: "@address"
        });
      } else {
        return null;
      }
    },
  },
  "desc": "成功"
}
View Code

PS:不得不吐槽下,准备好复制进来的文本和图片加载不出来,就一直转转转转转转转转<云计算中>~~~~~~~ @_@

原文地址:https://www.cnblogs.com/zousc/p/12074382.html