2.2.8 网络参考
fetch
Fetch API 提供了一个 JavaScript接口,用于访问和操纵HTTP管道的部分,例如请求和响应。它还提供了一个全局 fetch()方法,该方法提供了一种简单,合理的方式来跨网络异步获取资源。
进行 fetch 请求
fetch(url, {
body: JSON.stringify(data), // 请求的body信息
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, same-origin, *omit
headers: {
'user-agent': 'Mozilla/4.0 MDN Example',
'content-type': 'application/json'
},// (请求头)
method: 'POST', // *GET, POST, PUT, DELETE, 等。(请求方法)
mode: 'cors', // no-cors, cors, *same-origin
redirect: 'follow', // manual, *follow, error
referrer: 'no-referrer', // *client, no-referrer
})
.then(response => response.json()) // parses response to JSON
- body :请求的body信息
- cache
- default(表示fetch请求之前将检查下http的缓存)
- no-store(表示fetch请求将完全忽略http缓存的存在,这意味着请求之前将不再检查下http的缓存, 拿到响应后, 它也不会更新http缓存)
- no-cache(如果存在缓存,那么fetch将发送一个条件查询request和一个正常的request, 拿到响应后,它会更新http缓存)
- reload(表示fetch请求之前将忽略http缓存的存在, 但是请求拿到响应后,它将主动更新http缓存)
- force-cache(表示fetch请求不顾一切的依赖缓存, 即使缓存过期了,它依然从缓存中读取. 除非没有任何缓存, 那么它将发送一个正常的request)
- only-if-cached(表示fetch请求不顾一切的依赖缓存, 即使缓存过期了,它依然从缓存中读取. 如果没有缓存, 它将抛出网络错误(该设置只在mode为”same-origin”时有效).
- credentials : omit(缺省值,默认为该值)、same-origin(同源,便是同域请求才发送cookie)、include(任何请求都带cookie)
- headers : 请求头
- method : 请求方式
- mode :
fetch可以设置不同的模式使得请求有效. 模式可在fetch方法的第二个参数对象中定义.
可定义的模式如下:
- same-origin: 表示同域下可请求成功; 反之, 浏览器将拒绝发送本次fetch, 同时抛出错误 “TypeError: Failed to fetch(…)”.
- cors: 表示同域和带有CORS响应头的跨域下可请求成功. 其他请求将被拒绝.
- cors-with-forced-preflight: 表示在发出请求前, 将执行preflight检查.
- no-cors: 常用于跨域请求不带CORS响应头场景, 此时响应类型为 “opaque”.
- redirect :
- follow 默认,跟随跳转
- error 阻止并抛出异常
- manual 阻止重定向 (并不是像它的名字描述的那样)
- referrer :no-referrer
数据请求:
import React, {PureComponent} from 'react';
import {View,} from 'react-native';
import {loginDao} from '../loginDao';
export class pageComponent extends PureComponent {
componentDidMount() {
this.login('https://www.baidu.com/');
}
login(url) {
let opts = {
method:"GET"
}
fetch(url,opts)
.then((response) => {
return response.text();
})
.then((responseText) => {
alert(responseText)
})
.catch((error) => {
alert(error)
})
}
render() {
return (<View/>)
}
}