《React-Native系列》9、 Networking之fetch

来源:互联网 发布:淘宝开店店铺装修 编辑:程序博客网 时间:2024/05/14 17:20

今天,我们来看看RN怎么处理网络请求的,主要来看看fetch API。

还是,先来看看官网怎么说的。

Using Fetch 

React Native provides the Fetch API for your networking needs. Fetch will seem familiar if you have used XMLHttpRequest or other networking APIs before. You may refer to MDN's guide on Using Fetch for additional information.

Making requests 

In order to fetch content from an arbitrary URL, just pass the URL to fetch:

fetch('https://mywebsite.com/mydata.json')

Fetch also takes an optional second argument that allows you to customize the HTTP request. You may want to specify additional headers, or make a POST request:

fetch('https://mywebsite.com/endpoint/',{ method:'POST', headers:{'Accept':'application/json','Content-Type':'application/json',}, body: JSON.stringify({ firstParam:'yourValue', secondParam:'yourOtherValue',})})

Take a look at the Fetch Request docs for a full list of properties.

Handling the response 

The above examples show how you can make a request. In many cases, you will want to do something with the response.

Networking is an inherently asynchronous operation. Fetch methods will return a Promisethat make it straightforward to write code that works in an asynchronous manner:

getMoviesFromApiAsync(){return fetch('http://facebook.github.io/react-native/movies.json').then((response)=> response.json()).then((responseJson)=>{return responseJson.movies;}).catch((error)=>{ console.error(error);});}

You can also use the proposed ES2017 async/await syntax in a React Native app:

async getMoviesFromApi(){try { let response = await fetch('http://facebook.github.io/react-native/movies.json');let responseJson = await response.json();return responseJson.movies;}catch(error){ console.error(error);}}

Don't forget to catch any errors that may be thrown by fetch, otherwise they will be dropped silently.


我们可以看到fetch API主要使用了Promises来处理结果/回调。使用起来还是比较简单的。

关于Promise 可以参考:Promise对象


其实今天主要想介绍下官网没说的Headers、Request、Response 这三个对象,是不是熟悉的不能再熟悉了,对于做web开发的同学来说,但是我们今天还是来简单说下。

Headers

Headers是一个多映射的键值对,我们可以通过 new Headers()来创建请求头,参数可以是json对象。

主要的方法有:

append  

has      Headers的内容可以被检索

set / get / delete

使用栗子如下:

var headers = new Headers();headers.append("Content-Type", "text/plain");headers.append("X-Custom-Header", "value");// headers = new Headers({//   "Content-Type": "text/plain",//   "Content-Length": 10,// });console.log(headers.get("Content-Length")); // 10console.log(headers.has("Content-Type")); // trueconsole.log(headers.has("Set-Cookie")); // falseheaders.set("Content-Type", "text/html");headers.append("X-Custom-Header", "AnotherValue");console.log(headers.getAll("X-Custom-Header")); // ["value", "AnotherValue"]headers.delete("X-Custom-Header");console.log(headers.get("X-Custom-Header")); // []


Request

Request对象表示一次fetch 调用的请求信息。

method - 支持GET, POST, PUT, DELETE, HEAD
url - 请求的url
headers - 对应的Headers对象
reference - 请求的referrer 信息
mode - 可以设置 cors, no-cors, same-origin
credentials - 设置cookies是否随请求一起发送。可以设置:omit, same-origin
integrity - subresource完整性值(integrity value)
cache - 设置cache模式(default, reload, no-cache)


最简单的 Request 当然是一个URL,可以通过URL来GET一个资源。

var req = new Request("/index.html");console.log(req.method); // "GET"console.log(req.url); // "http://example.com/index.html"

你也可以将一个建好的Request对象传给构造函数,这样将复制出一个新的Request。
var copy = new Request(req);console.log(copy.method); // "GET"console.log(copy.url); // "http://example.com/index.html"

完整的栗子:

var request = new Request('http://127.0.0.1:8080/order/query', {          method: 'POST',          headers: headers,          body: JSON.stringify({channel:1,cityid:101}),        });

Response

Response实例通常在fetch()的回调中获得,Response 代表响应,fetch的then方法接受一个Response实例。

Response中最常见的成员是status(一个整数默认值是200)和statusText(默认值是"OK"),对应HTTP请求的status和reason。还有一个"ok"属性,当status为2xx的时候它是true。


Response可以配置的参数:
type - 类型,支持:basic, cors
url
useFinalURL - Boolean 值,代表url是否是最终URL
status - 状态码(例如:200,404)
ok - Boolean值,代表成功响应(status值在200-299之间)
statusText - 状态值(例如:OK)
headers - 与响应相关联的Headers对象


Response 提供的方法如下:
clone() - 创建一个新的Response克隆对象
error() - 返回一个新的,与网络错误相关的Response对象
redirect() - 重定向,使用新的URL创建新的Response对象
arrayBuffer() - Returns a promise that resolves with an ArrayBuffer
blob() - 返回一个promise,resolves是一个Blob
formData() - 返回一个promise, resolves是一个FormData对象
json() - 返回一个promise,resolves是一个JSON对象
text() - 返回一个promise,resolves是一个USVString(text)

一个完整的fetch栗子:

        const headers = new Headers();        headers.set( 'os' , 'ios');        headers.set( 'channel' , '1');        fetch('http://127.0.0.1:8080/order/query', {          method: 'POST',          headers: headers,          body: JSON.stringify({cityid:1}),        })        .then((response) => response.json())        .then((json) => {          //a JS Object        }).catch((error) => {          //error        });


参考:http://www.cnblogs.com/hsprout/p/5504053.html

           http://www.w3ctech.com/topic/854


0 0
原创粉丝点击