fetch请求参数
get请求方式的参数传递
特性: 更加简单的数据获取方式,功能更强大,更灵活,可以看作是xhr的升级版 。基于promise实现
常用配置选项
method:HTTP 请求方法,默认GET(GET,POST,PUT,DELETE)
body:HTTP的请求参数
headers:HTTP请求头默认为{}
1,
fetch('/abc?id=123').then(data=>{
//此处: 返回的是promise对象分为两种情况
//1 text() 属于fetchAPI的一部分,返回的是一个promise的实例对象,用于获取平台返回的数据,
//2 json() 若是json需要JSON.parse(data)
return data.text();
//return data.json();
}).then(ret=>{
//这里得到的才是最终的数据
console.log(ret)
})
fetch('/abc?id=123').then(data=>{
//此处: 返回的是promise对象分为两种情况
//1 text() 属于fetchAPI的一部分,返回的是一个promise的实例对象,用于获取平台返回的数据,
//2 json() 若是json需要JSON.parse(data)
return data.text();
//return data.json();
}).then(ret=>{
//这里得到的才是最终的数据
console.log(ret)
})
2,
fetch('/abc/123',{methoc:'get'}).then(data=>{
//此处: 返回的是promise对象分为两种情况
//1 text() 属于fetchAPI的一部分,返回的是一个promise的实例对象,用于获取平台返回的数据,
//2 json() 若是json需要JSON.parse(data)
return data.text();
//return data.json();
}).then(ret=>{
//这里得到的才是最终的数据
console.log(ret)
})
post请求方式的参数传递
fetch('/books',{
method:'POST',
body:'name=lisi&pwd=123',
headers:{
"Content-Type":"application/x-www-form-urlencoded",
}
}).then(data=>{
return data.text()
}).then(res=>{
console.log(res)
})
put请求方式的参数传递
fetch('/books/123',{
method:'PUT',
body:JSON.stringify({name='lisi',age=123}),
headers:{
"Content-Type":"application/json",
}
}).then(data=>{
return data.text()
}).then(res=>{
console.log(res)
})
axios基本用法
axios用法链接
axios封装
async/await使用
async/await是ES7引入的新语法,可以更加方便的进行异步操作,
async关键字用于函数上(async函数的返回值是Promise的实例对象)
await关键字用于async函数当中(await可以得到异步的结果)
async functiion queryData(id){
const ret = await axios.get('/data')
return ret;
}
queryData.then(ret=>{
console.log(ret)
})
多个异步请求
async functiion queryData(id){
const info = await axios.get('/data')
const let = await axios.get('/data1?info='+info.data)
return ret;
}
queryData.then(ret=>{
console.log(ret)
})