fetch的使用
React Native提供了一套用来访问网络的方法:Fetch API。
developer.mozilla.org/en-US/docs/…
fetch参数:
- url:链接地址
- method:POST / GET
- header:头部信息
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;',
'Content-Type': 'application/json;charset=utf-8;'
- credentials:'include',fetch请求携带cookie信息
- body:参数
使用方式:
- 无参,默认方式
fetch('https://api.apiopen.top/todayVideo').then(response=>{
return response.json()
}).then(res=>{
console.log(res)
}).catch(error=>{
console.log(error)
})
- 带参,以post为例 - 提交普通表单
const str = 'name=test&age=21'
fetch('https://api.apiopen.top/todayVideo', {
method: 'POST',
body: str,
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;',
},
credentials: 'include', // fetch请求携带cookie信息
})
.then(response => response.json())
.then((res) => {//res为上边解析好的json
console.log(res);
this.setState({
title:res.title,
desc:res.desc,
})
})
.catch((error) => {
console.log(error);
})
- 带参,以post为例 - 提交json
const data={
name:'test',
age:21,
}
fetch('https://api.apiopen.top/todayVideo', {
method: 'POST',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json;charset=utf-8;'
},
credentials: 'include', // fetch请求携带cookie信息
})
.then(response => response.json())
.then((res) => {//res为上边解析好的json
console.log(res);
this.setState({
title:res.title,
desc:res.desc,
})
})
.catch((error) => {
console.log(error);
})