axios的使用

134 阅读1分钟

axios

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

可以直接用axios实例

axios.get('/user?ID=12345')

也可以用axios再创建一个instance实例

const instance = axios.create({
  baseURL: 'https://some-domain.com/api/',
  timeout: 1000,
  headers: {'X-Custom-Header': 'foobar'}
});
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
instance.get('/longRequest', {
  timeout: 5000
});

axios的方法执行返回promise,然后用这个promise then 和 catch请求结果

// axios.get('/user?ID=12345') 下面和这个一样的
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);
  });
或
// 发送 POST 请求
axios({
  method: 'post',
  url: '/user/12345',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
});

请求路径组成

/register/123 ?plan=private #777

path params query hash

post 请求内容在body里 data

d39c4f50628966bd23e633c035ae760.jpg

拦截器

// 添加请求拦截器
axios.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    return config;
  }, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  });

// 添加响应拦截器
axios.interceptors.response.use(function (response) {
    // 对响应数据做点什么
    return response;
  }, function (error) {
    // 对响应错误做点什么
    return Promise.reject(error);
  });

项目中使用

import axios from 'axios';

const instance = axios.create({
baseURL: 'http://apis.imooc.com/api/'
})

// 发消息中统一添加icode
instance.interceptors.request.use( config => {
console.log('request config', config);
const mukeCode = '5CD4944B827AC23C';
if (config.method === 'get') {
  config.params = {
    ...config.params,
    icode: mukeCode
  }
} else {
  config.data = {
    ...config.data,
    icode: mukeCode
  }
}
return config
})

export default instance;

axios 发送请求

1、axios发送get请求,参数在query里。

axios不支持get请求把参数放到body里,如果实在需要可以用fetch

async getOrgList() {
        let res = await this.$axios.get('/user/b/getOrgList', {
            params: {
                pageNo: 1,
                pageSize: 99,
                type: 6
            }
        })
        this.researchList = res.data.retData.list
    },

2、axios发送post请求,参数写在body里

async AddOrModifyIt() {
        await this.$axios.post('/project/b/project/updateProjectOrg', {
            leader: this.leader,
            oldOrgId: this.orgPrimaryId,
            planSubjectNum: this.planSubjectNum,
            sectionId: this.mainResearchValue.sectionId,
            userId: this.mainResearchValue.userId,
            userName: this.mainResearchValue.name
        })
    },

3、axios发送post请求,参数写在query里

async deleteRow(index, row) {
        await this.$axios.post(
            '/project/b/project/deleteProjectOrgById',
            {},
            {
                params: {
                    orgPrimaryId: this.orgPrimaryId
                }
            }
        )
    },

http请求参数之Query String Parameters、Form Data、Request Payload

(1)、 Query String Parameters get请求常用

当发起一次GET请求时,参数会以url string的形式进行传递。即?后的字符串则为其请求参数,并以&作为分隔符。

如下http请求报文头:

// General
Request URL: http://foo.com?x=1&y=2
Request Method: GET

123

wwww.com/productInfo…

Query String Paramters
status:ACTIVE
all:true

(2)、Request Payload post请求常用

当发起一次POST请求时,若content-type为application/json,则参数会以Request Payload的形式进行传递(显然的,数据格式为JSON),不会显式出现在请求url中。

image.png 如下http请求报头:

// General
Request URL: http://foo.com
Request Method: POST

123

// Request Headers
content-type: application/json; charset=UTF-8

// Request Payload
{typeCode: "demandType"}

origin_img_v2_f47d6e0c-0e9c-43d1-b9d8-ce19309c3c1g.png

(3)、Form Data\

请求后端接口参数少的时候 后端用form data格式

FormData 接口提供了一种表示表单数据的键值对 key/value 的构造方式,并且可以轻松的将数据通过XMLHttpRequest.send() 方法发送出去,本接口和此方法都相当简单直接。如果送出时的编码类型被设为 "multipart/form-data",它会使用和表单一样的格式。

当发起一次POST请求时,若未指定content-type,则默认content-type为application/x-www-form-urlencoded。即参数会以Form Data的形式进行传递,不会显式出现在请求url中。

ykvklgMVjL.jpg 如下http请求报头:

// General
Request URL: http://foo.com
Request Method: POST

123

// Request Headers
content-type: application/x-www-form-urlencoded; charset=UTF-8

// Form Data
token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyE2MzAzODkzNTIsI
appCode: 7641-4467-b1b9-047bc4447e00

origin_img_v2_dc34c75f-7fdd-4da2-b7ce-3112deb8335g.png

export function objectToFormData (obj, form, namespace) {
  const fd = form || new FormData();
  let formKey;
  for (const property in obj) {
    if (obj.hasOwnProperty(property)) {
      const key = Array.isArray(obj) ? '[]' : `[${property}]`;
      if (namespace) {
        formKey = namespace + key;
      } else {
        formKey = property;
      }
      // if the property is an object, but not a File, use recursivity.
      if (typeof obj[property] === 'object' && !(obj[property] instanceof File)) {
        objectToFormData(obj[property], fd, formKey);
      } else {
        // if it's a string or a File object
        fd.append(formKey, obj[property]);
      }
    }
  }
  return fd;
}

// 普通json转为formdata
 const params = {
    releaseApplyId: this.releaseApplyId,
    deployCommand: this.form.deployCommand
  };
  const formData = objectToFormData(params);