Axios 整理常用形式及涉及的参数

发布于:2025-08-29 ⋅ 阅读:(20) ⋅ 点赞:(0)

一、axios get请求

//形如
axios.get(url[, config])
  .then(response => {
    // 处理响应
  })
  .catch(error => {
    // 处理错误
  });
//无 config 的情况下,
axios.get('https://api.example.com/data')
  .then(response => {
   // 处理响应
  }) .catch(error => {
   // 处理错误
  });
  1. url:即请求api 链接;
  2. [, config]:表示config 可有可无

axios get请求 一 config 参数(常用)

// An highlighted block
axios.get('https://api.example.com/data',{
	//传递的数据:方式二选一;
	//我们通过 `params` 对象传递了查询参数,
	//实际上请求的URL会变成 'https://api.example.com/data?username=test'。
	params:{
		"username":"test",
	},
	headers:{
		"Content-Type":"application/json",
	},
	timeout:1000,//请求超时设置
})
  .then(response => {
   // 处理响应
  }) .catch(error => {
   // 处理错误
  });

二、axios post

//形如
axios.post(url,data[, config])
  .then(response => {
    // 处理响应
  })
  .catch(error => {
    // 处理错误
  });
//无 config 的情况下,
axios.post('https://api.example.com/data',{
	firstName: 'Fred',
    lastName: 'Flintstone'
})
  .then(response => {
   // 处理响应
  }) .catch(error => {
   // 处理错误
  });
  1. url:即请求api 链接;
  2. data:传递的参数,object { } 形式;
  3. [, config]:表示config 可有可无

axios post请求 一 config 参数(常用)


axios.post('https://api.example.com/data',data,{
	//传递的数据:方式二选一;
	data: {
   		 firstName: 'Fred'
 	},
	headers:{
		"Content-Type":"application/json",
	},
	timeout:1000,//请求超时设置
})
  .then(response => {
   // 处理响应
  }) .catch(error => {
   // 处理错误
  });

三、axios() 发起请求

//形如
axios({
	//config内容 常用字段
	method:'get/post',//常用的
	url:'/data',
	baseURL: 'https://api.example.com',
	//params 用于 get 传参数
	params:{},
	//data 用于 post 传递参数
	data:{},
	headers:{},
	timeout:100,
	
})
  .then(response => {
   // 处理响应
  }) .catch(error => {
   // 处理错误
  });

四、axios 创建实例