fetch的使用

266 阅读1分钟

fetch的使用

React Native提供了一套用来访问网络的方法:Fetch API。

developer.mozilla.org/en-US/docs/…

fetch参数:

  1. url:链接地址
  2. method:POST / GET
  3. header:头部信息
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;',
'Content-Type': 'application/json;charset=utf-8;'
  1. credentials:'include',fetch请求携带cookie信息
  2. body:参数

使用方式:

  1. 无参,默认方式
fetch('https://api.apiopen.top/todayVideo').then(response=>{
    return response.json() 
}).then(res=>{
    console.log(res) 
}).catch(error=>{ 
    console.log(error)
})

  1. 带参,以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);
      })
  1. 带参,以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);
      })