React项目模板-axios的使用

2019-05-10  本文已影响0人  stevekeol

项目源地址

axios

基于Promise的用于浏览器和Node.js的http客户端.

特点

安装

npm install axios --save

一、基本使用

发起get请求:

//初始写法
axios.get('/user?ID=12345')
  .then((res) => console.log(res);})
  .catch((err) => console.log(error);});

//改进写法(1)
let option = {
    params: {
      ID: 12345
    }
}
axios.get('/user', option)
  .then((res) => console.log(res);})
  .catch((err) => console.log(error);});

//改进写法(2)-- 推荐写法
let option = {
    url: '/user',
    params: {
      ID: 12345
    }
}
axios.get(option)
  .then((res) => console.log(res);})
  .catch((err) => console.log(error);});

发起post请求

let option = {
    url: '/user',
    data: {
       firstName: 'Fred',
       lastName: 'Flintstone'       
    }
}
axios.post(option)
  .then((res) => console.log(res))
  .catch((err) => console.log(err));

二、进阶使用

获取远程图片

let option = {
  url:'http://bit.ly/2mTM3nY',
  responseType:'stream'
}

axios.get(option)
  .then((res) => res.data.pipe(fs.createWriteStream('ada_lovelace.jpg')));

使用axios.all并发请求

function getUserOne() {
  return axios.get('/user/123');
}
function getUseAnother() {
  return axios.get('/user/456');
}
 
axios.all([getUserOne(), getUseAnother()])
  .then(axios.spread((resOne, resAnother) => {
    console.log(resOne.data);
    console.log(resAnother.data);
  }));

使用axios.cerate创建一个拥有通用配置的axios实例

三、高级使用

请求配置项

{
  url: '/user',
  method: 'get', // default
  baseURL: 'https://some-domain.com/api/',
  transformRequest: [function (data, headers) {
    //do sothing
    return data;
  }],
  transformResponse: [function (data) {
    //do sothing
    return data;
  }],
 
  headers: {'X-Requested-With': 'XMLHttpRequest'},
  params: {
    ID: 12345
  },
  paramsSerializer: function(params) {
    return Qs.stringify(params, {arrayFormat: 'brackets'})
  },
  data: {
    firstName: 'Fred'
  },
  timeout: 1000,
  withCredentials: false, // default
  adapter: function (config) {
    /* ... */
  },
  auth: {
    username: 'janedoe',
    password: 's00pers3cret'
  },
  responseType: 'json', // default
  xsrfCookieName: 'XSRF-TOKEN', // default
  xsrfHeaderName: 'X-XSRF-TOKEN', // default
  onUploadProgress: function (progressEvent) {
    //do something
  },
  onDownloadProgress: function (progressEvent) {
    // Do whatever you want with the native progress event
  },
  maxContentLength: 2000,
  validateStatus: function (status) {
    return status >= 200 && status < 300; // default
  },
  maxRedirects: 5, // default
  socketPath: null, // default
  httpAgent: new http.Agent({ keepAlive: true }),
  httpsAgent: new https.Agent({ keepAlive: true }),
  proxy: {
    host: '127.0.0.1',
    port: 9000,
    auth: {
      username: 'mikeymike',
      password: 'rapunz3l'
    }
  },
  cancelToken: new CancelToken(function (cancel) {
  })
}

响应的组成(res的结构)

{
  data: {},
  status: 200,
  statusText: 'OK',
  headers: {},
  config: {}, //req中的config
  request: {}
}

附录

问题一:

//OK
export function get() {
  return new Promise((resolve) => {
    axios.get('http://mock-api.com/WmnE4LgJ.mock/getPhone')
      .then((res) => resolve(res.data ? res.data : []));
  });
}
//报错
export function get() {
  const initialOption = {
    url: 'http://mock-api.com/WmnE4LgJ.mock/getPhone'
  };
  return new Promise((resolve) => {
    axios.get(initialOption)
      .then((res) => resolve(res.data ? res.data : []));
  });
}
报错信息
//这样是OK的
export function get() {
  const initialOption = {
    method: 'get',
    url: 'http://mock-api.com/WmnE4LgJ.mock/getPhone'
  };
  return new Promise((resolve) => {
    axios(initialOption)
      .then((res) => resolve(res.data ? res.data : []));
  });
}
//这样也是可以的
export function get() {
  const initialOption = {
    method: 'get',
    baseURL: config.baseURL,
    url: '/getPhone'
  };
  return new Promise((resolve) => {
    axios(initialOption)
      .then((res) => resolve(res.data ? res.data : []));
  });
}

附录二

// actions/index.js
export const FETCH_ROMOTE_DATA = 'FETCH_ROMOTE_DATA';

export function fetchRemoteData() {
  const option = {
    url: '/getPhone'
  };
  return {
    type: FETCH_ROMOTE_DATA,
    payload: axios.get(option)
  };
}

/**
 * 1. 调用axios.get(),可以传入参数option={url: '/getPhone', params: {ID: '12345'}}
 * 2. 调用axios.post(),可以传入参数option={url: '/postUserInfo', data: {name: 'zhang', age: '18'}}
 */

// utils/axios.js
export function get(option) {
  const initialOption = {
    method: 'get',
    baseURL: config.baseURL
  };
  const _option = Object.assign(initialOption, option);
  return new Promise((resolve) => {
    axios(_option)
      .then((res) => resolve(res.data ? res.data : []));
  });
}

export function post(option) {
  const initialOption = {
    method: 'post',
    baseURL: config.baseURL
  };
  const _option = Object.assign(initialOption, option);
  return new Promise((resolve) => {
    axios(_option)
      .then((res) => resolve(res.data ? res.data : []));
  });
}


//reducers/getRemoteData.js
略
上一篇下一篇

猜你喜欢

热点阅读