Loading

个人技术总结——Axios使用总结

作业基本信息

这个作业属于哪个课程 2021春软件工程实践|S班 (福州大学)
这个作业要求在哪里 软件工程实践总结&个人技术博客
这个作业的目标 从个人技术学习角度和团队开发技术角度中选择最擅长的一个相关技术,进行分析描述并总结
其他参考文献 Axios中文说明

技术概述

Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。

技术详述

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);
  });

执行多个并发请求

function getUserAccount() {
  return axios.get('/user/12345');
}

function getUserPermissions() {
  return axios.get('/user/12345/permissions');
}

axios.all([getUserAccount(), getUserPermissions()])
  .then(axios.spread(function (acct, perms) {
    // 两个请求现在都执行完成
  }));

遇到的问题与解决过程

问题

运用axios进行发送请求后获取不到数据。

解决过程

基本配置

import axios from 'axios'

// 创建axios实例
const service = axios.create({
  baseURL: url,
  timeout: 5000,
  withCredentials: true // 允许携带cookie
})

请求拦截器

service.interceptors.request.use(config => {
    config.headers.common['token'] = localStorage.getItem(“token”);
    return config
},err => {
    //请求出错的处理函数
    return Promise.reject(err)
})

封装为函数

export function delBlog(id) {
  return request({
    url: '/blog',
    method: 'delete',
    params:{blogId:id}
  })
}

总结

  • 获取不到数据时首先检查url是否正确。
  • 对axios设置baseURL方便维护,不易出错。

参考文献

Axios中文说明

posted @ 2021-06-28 21:07  -ways-  阅读(217)  评论(3编辑  收藏  举报