fetch,axios简介与语法
2024-10-20 04:27:49
fetch简介&语法
留心:像之前的XMLHttpRequest 但并不真的是,而是代替的
#概念:fetch是ecma组织基于promise开发http api ,用来代替xhr
#语法:fetch函数类型,有两个实参,第一个实参是请求地址必须写,第二个是对象类型选写、里面的键是固定的、例如method字符串、headers对象类型(1请求头藏接口请求参数2请求头请求数据编码)、body键声明post请求参数(默认字符串类型数据按照get传参形式去写 参数名=值&.....&参数名=值
fetch(请求地址, {
method: 'get/post',
headers: {
'token': '用户登录成功的身份标识',
'content-type': 'application/x-www-form-urlencoded',
....
},
body: '参数名=值&.....&参数名=值'
// ...
})
#get
fetch(请求地址).then(res => res.json()).then(res => console.log(res))
#post
fetch(请求地址, {
method: 'post',
# 针对post请求传递字符串类型
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: '参数名=值&.....&参数名=值'
# post请求传递JSON数据类型
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
参数名: '数据',
参数名: '数据'
})
})
.then(res => res.json())
.then(res => console.log(res))
axios简介&语法
Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。
语法
说明
#axios可以当方法使用、也可以当对象使用,还可以n种操作
#axios可以当方法使用:有一个实参对象类型必须,里面有固定的键 method字符串, headers对象类型, data也是根据请求方式确定类型, timeout请求超时等等
#留心:axios返回promise对象,直接通过.then获取接口数据,但是第一次then返回的HTTP相关信息、接口数据在data键中,因此需要写res.data才能获取接口数据。推荐优化.then(res => res.data).then(res=> res)1 axios函数(较多
# 结构
axios({
url: '',
method: '',
headers: {},
data: 类型根据请求方式来定, // post 如果gert就在url后面写?参数名=值 或者 用params对象类型
params: {参数名:值}
...
})
# get
axios({
方法1
url: '请求地址?参数名=值',
方法2
url: '请求地址',
params: {
参数名:值,
}
method: 'get',
headers: {}
...
})
# post
axios({
url: '',
method: '',
headers: {},
data: 类型根据请求方式来定,
})
最新文章
- JS中的decodeURIComponent和encodeURIComponent
- chrome使用技巧
- 北大ACM(POJ1006-Biorhythms)
- js 获取时间 new Date()详细介绍
- Hacker(15)----嗅探原理
- MassMutual Interview Questions
- JavaScript设计模式之一Interface接口
- Https协议与HttpClient的实现
- HTML文本框样式大全
- css3 自定义滚动条样式
- dump增加的表数据
- python生成语谱图
- python os.chdir() 用法
- UVALive 4174
- jQuery属性操作之.attr()
- USB描述符【整理】
- [C++] Memory Retrieval(内存检索)
- 【modelsim常见问题集锦】Can't launch the ModelSim-Altera software
- [elk]elasticsearch5.0及head插件安装
- OpenStack-Mitaka