axios

163 阅读1分钟

Get请求

  • 方式一
axios.get('/user?ID=12345')
  .then(function (res) {
  })
  .catch(function (error) {
    console.log(error);
  })
  .finally(function () {
    
  });
  • 方式二
axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
  
  })
  .catch(function (error) {
    console.log(error);
  })
  .finally(function () {
    
  });
  • 方式三 使用async...await
async function getUser() {
  try {
    const response = await axios.get('/user?ID=12345');
  } catch (error) {
    console.error(error);
  }
}
  • 方式四 Get是默认的请求方法
axios('/user/12345');

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实例

const instance = axios.create({
  baseURL: 'https://some-domain.com/api/',
  timeout: 1000,
  headers: {'X-Custom-Header': 'foobar'}
});