发表于: 2020-08-17 21:27:29

2 2295


今天完成的事情:

安装配置axios


明天计划的事情:

完成登录页面请求


遇到的问题:

跨域配置不太明白

post方法结果是404


收获:


Axios

一个基于 promise(异步编程的解决方案,相当于一个构造函数)的 HTTP 库。可以用来创建http请求、拦截请求和响应、转换请求数据和响应数据、取消请求、自动转换 JSON 数据等。

在vue-cli项目中使用

第一步:

安装

第二步:

在src/main.js中配置 axios

import axios from 'axios'//引入

import VueAxios from 'vue-axios'

Vue.use(VueAxios, axios)

//Vue.prototype.$axios = axios;//全局注册

new Vue({

  el: '#app',

  axios,

  components: { App },

  template: '<App/>'

})


第三步:

前后端分离的开发方式通常还需跨域配置,根据实际情况修改config目录下的index.js文件(没有则自己创建)中的proxyTable
如后端请求地址是http://dev.admin.carrots.ptteng.com/,所有api的接口url都以/api开头。所以首先需要匹配所有以/api开头的.然后修改target的地址为http://dev.admin.carrots.ptteng.com/。最后修改pathRewrite地址。将前缀 '^api' 转为 '/api'。如果本身的接口地址就有 '/api' 这种通用前缀,就可以把 pathRewrite 删掉。注意这个方式只能在开发环境中使用。

```

proxyTable: { 

  '/api': {  //使用"/api"来代替"http://dev.admin.carrots.ptteng.com/" 

    target: 'http://dev.admin.carrots.ptteng.com/', //源地址 

    changeOrigin: true, //改变源 

    pathRewrite: { 

      '^/api': '/api’//路径重写 

      } 

  } 

}

```


第四步

执行请求
使用axios跨域请求数据时直接使用“/api”
三种get请求方法:

Vue.axios.get(api)

.then((response) => {  

console.log(response.data)

})

this.axios.get(api)

.then((response) => {  

console.log(response.data)

})

this.$http.get(api)

.then((response) => {  

console.log(response.data)

})


post请求

vue.axios.post('/api/a/login, {    

    firstName: 'Fred',    

    lastName: 'Flintstone' 

 }) 

    .then(function (response) {    

        console.log(response);  

    }) 

    .catch(function (error) {

        console.log(error);  

    });




返回列表 返回列表
评论

    分享到