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

一、axios get请求

javascript 复制代码
//形如
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 可有可无

javascript 复制代码
// 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

javascript 复制代码
//形如
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 可有可无

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

三、axios() 发起请求

javascript 复制代码
//形如
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 创建实例

相关推荐
利刃大大18 小时前
【Vue】自定义指令directives && 指令钩子 && IntersectionObserver
前端·javascript·vue.js
共享家95271 天前
搭建 AI 聊天机器人:”我的人生我做主“
前端·javascript·css·python·pycharm·html·状态模式
摘星编程1 天前
OpenHarmony环境下React Native:自定义useTruncate文本截断
javascript·react native·react.js
Duang007_1 天前
【LeetCodeHot100 超详细Agent启发版本】字母异位词分组 (Group Anagrams)
开发语言·javascript·人工智能·python
2601_949868361 天前
Flutter for OpenHarmony 电子合同签署App实战 - 主入口实现
开发语言·javascript·flutter
m0_748229991 天前
Vue2 vs Vue3:核心差异全解析
前端·javascript·vue.js
xiaoxue..1 天前
React 手写实现的 KeepAlive 组件
前端·javascript·react.js·面试
摘星编程1 天前
在OpenHarmony上用React Native:自定义useHighlight关键词高亮
javascript·react native·react.js
2601_949613021 天前
flutter_for_openharmony家庭药箱管理app实战+用药知识详情实现
android·javascript·flutter
一起养小猫1 天前
Flutter for OpenHarmony 实战 表单处理与验证完整指南
android·开发语言·前端·javascript·flutter·harmonyos