博主
258
258
258
258
专辑

第八节 Vue脚手架之安装axios

亮子 2021-06-09 09:33:10 7213 0 0 0

既然vue是前后端分离的,那么前端和后端的数据交换,就需要一个js库来实现,在这里我们选择的是axios,安装命令如下:

npm install axios --save

安装完成后,要想使用axios库,也需要在main.js文件中增加如下配置代码:

// file:main.js
import Vue from 'vue'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
//--1
import axios from 'axios'
import App from './App.vue'

//--2
axios.defaults.baseURL="http://localhost:8080";
Vue.prototype.$http = axios

Vue.use(ElementUI)

new Vue({
  el: '#app',
  render: h => h(App)
})

axios的请求可以使用下面的范例:

  • 异步模式:
    axios
      .get('https://api.coindesk.com/v1/bpi/currentprice.json')
      .then(response => {
        this.info = response.data.bpi
      })
      .catch(error => {
        console.log(error)
        this.errored = true
      })
      .finally(() => this.loading = false)
  • 同步模式:
//使用 asyns/await 
async getHistoryData (data) {
 try {
   let res = await axios.get('/api/survey/list/', {
     params: data
   })
   this.tableData = res.data.result
   this.totalData = res.data.count
 } catch (err) {
   console.log(err)
   alert('请求出错!')
 }
}

执行 GET 请求

// 为给定 ID 的 user 创建请求
axios.get('/user?ID=12345')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

// 上面的请求也可以这样做
axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

执行 POST 请求

axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

axios拦截器

1、目录结构

图片alt

2、api/request.js文件

import axios from "axios"

// 创建axios实例
const service = axios.create({
    baseURL: 'http://localhost:8000',  // api的base_url
    timeout: 5000  // 请求超时时间
})

// 拦截请求
service.interceptors.request.use(
    config => {
        console.log("request url="+config.url)
        // config.baseURL = '/user/'
        // config.withCredentials = true // 允许携带token ,这个是解决跨域产生的相关问题
        config.timeout = 6000
        let token = sessionStorage.getItem('token')
        if (token) {
            config.headers.Authorization = token;
            config.headers = {
                'token': token,
                // 'Content-Type': 'application/x-www-form-urlencoded'
            }
        }
        return config
    },
    error => {
        return Promise.reject(error)
    }
)

// 拦截响应
service.interceptors.response.use(
    response => {
        // 定时刷新token
        console.log(response.data)
        return response
    },
    error => {
        return Promise.reject(error)
    }
)

export default service

3、api/api.js文件

import service from './request'

export const login = data => {
    return service({
        url: '/user/login',
        method: 'post',
        data
    })
};

4、api/api.js文件的使用

    import {login} from '../api/api.js'


        methods: {
            submitForm(formName) {
                //
                this.$refs[formName].validate((valid) => {
                  if (valid) {
                    // 进行登录
                    let data = new FormData()
                    data.append('username',this.ruleForm.username)
                    data.append('password',this.ruleForm.password)
                    login(data)
                    .then(res => {
                        console.log(res)
                        this.$router.push("/")
                    })
                    .catch(err => {
                        console.log(err)
                    })
                    //this.handleLogin(this.ruleForm.username, this.ruleForm.password)P
                  } else {
                    console.log('error submit!!');
                    return false;
                  }
                });
            }
        }

5、同步调用

//index.vue
import {login} from '../api/api.js'
export default {
    created: async function () {
        const params = {
            card_no: '111'
        };
        let res = await login(params);
        console.log(res);
    }
}

axios官网

http://www.axios-js.com/zh-cn/docs/

参考文章