Dowemo
0 0 0 0

Recently, react native development has encountered such a fetch request,, which was more than ajax before the fetch request.

It isn't really a good idea, so spend time baidu and see how you use it. By the way, we need to encapsulate the network request.

A get and post methods that facilitate the following invocation.

No more words, the point of the point:

In development, loading data from the network has always been focused and difficult, especially if the corresponding detail optimization is done, which is usually

How to load network data?

Reaction native is usually passed throughAjaxGet data from the servercomponentDidMountMethod to createAjexRequest, wait until the request succeeded,

And use it.This. Setstate.Method UI

, what's.

  • fetchNot yet. W3c The specification is determined by whatagResponsible for development. AjaxIt's different. It's. APIIt isn't an event mechanism.

  • Popular. Promise ( mdn promise )

  • Format:

 fetch(url, init)
. then((response) => { // 数据解析方式
 }). then((responseData) => { // 获取到的数据处理
 }). catch((error) => { // 错误处理
 }). done();
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • In the above example initIt's an object, he contains:
    • Method: request mode ( get, post, put, etc. ).
    • Headers: use the header object to use this parameter.
    • Body: data that needs to be sent
    • Mode: settings ( no-cors. Same-origin ).
    • Cache: caching options ( default, no-store, reload, no-cache, force-cache, or only-if-cached )

  • Body: objects, with json. Stringify ( % 7b. % ), won't be able to automatically encapsulate objects into formdata forms in jquery, and fetch won't.
  • The mode property controls master, where same-origin (, ), no-cors ( default, can request resources for other domai &,
  • Can't access properties in response and cros ( allow, you can obtain third-party data, and need to be accessed for access ).
  • Use fetch to note the browser version, but react-native doesn't need to be considered.
  • responseObjects can have several ways of parsing

    • Arraybuffer ( )
    • Json ( )
    • Text ( )
    • Blob ( )
    • Formdata ( )
  • The following is a basic request, passing in only one parameter, by default GETMode request

 fetch(url)
. then((response) => response.json())//json方式解析,如果是text就是 response.text(). then((responseData) => { // 获取到的数据处理
 }). catch((error) => { // 错误处理 
 }). done();
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • We usually use a request for form submission. POSTIn the way.

How to:

 fetch(url, {
 method: "POST",
 headers: {
 "Content-Type": "application/x-www-form-urlencoded" }
 body:"key1=value&key2=value...&keyN=value" })
. then((response) => { // 数据解析方式
 }). then((responseData) => { // 获取到的数据处理
 }). catch((error) => { // 错误处理
 }). done();
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • In JQueryIn, the incoming object framework is automatically encapsulated into formDataIn the form, but in fetchThere's no function, so we need it.
  • Initialize itself. FormDataPass directly to body( added: formdata can also pass byte stream implementation upload image function )

let formData = new FormData();
 formData.append("参数", "值");
 formData.append("参数", "值");
 fetch(url, {
 method:'POST, headers:{},
 body:formData,
 }).then((response)=>{
 if (response.ok) {
 return response.json();
 }
 }).then((json)=>{
 alert(JSON.stringify(json));
 }).catch.((error)=>{
 console.error(error);
 })
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

  • Application/x-www-form-urlencoded: form data is encoded as a name value pair. This is the standard encoding format.
  • Multipart/form-data: form data is encoded as a message that corresponds to one part of each control on the page.
  • Text/plain: the form data is encoded in plain text, with no control or lattice character.
  • FetchThe default is without requests. cookieIf you need to set credentials: 'include '.

, get http header information

 console.log(response.headers.get('Content-Type'));
 ... console.log(response.headers.get('Date'));
  • 1
  • 2
  • 3
  • 4
  • 1
  • 2
  • 3
  • 4
Note:Using the fetch request, if the returned chinese character is malformed, you can set the following code solution on the server side:
="text/html; charset = utf-8"

Three, fetchrequest uses the following:

get method:
get(url, func=false) {
 return fetch(url) //GET方式 获取Json数据 .then((response) => {
 let data = response.json(); //解析数据为 json格式return data; //传递数据给下一步})
. then((json_data) => { //接收刚刚获取到的数据 //如果有回调if( false!==func ){
 func(json_data);}
 })
. catch ((error) => { //fetch开始,到最后一个then,有错误出现,则会捕捉错误。console.warn('Catch info');console.error(error);});},
As shown: url for the url we requestThe steps of encapsulation are to follow the steps given by official steps.Post request:
post(url, ini_json={}, unlisted=false) {
 let token = '', //身份识别码headers = { //http请求头'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},body = '', //用于post的数据 func = undefined !== ini_json.func? ini_json.func : false; //回调函数//请求时,请求地址带上token if( false=== unlisted ){
 token = unlisted;//这里是token}
 if( undefined !== ini_json.headers ){
 headers = init_json.headers;}
 //暂不支持数组传输,已建议同类数据以逗号分隔if( undefined !== ini_json.data ){
 //如果有数据for(let i in ini_json.data){
 body += i + '=' + encodeURIComponent(ini_json.data[i]) + '&';}
 }
 return fetch(url, {
 method: 'POST', headers: headers, body: body,})
. then((response) => {
 let data = response.json(); //解析数据为 json格式return data; //传递数据给下一步})
. then((json_data) => { //接收刚刚获取到的数据 //如果有回调if( false!==func ){
 func(json_data);}
 })
. catch ((error) => { //fetch开始,到最后一个then,有错误出现,则会捕捉错误。console.warn('Catch info');console.error(error);});}
}
As shown: this post request adds a number of business logic. Include token when requested.The steps are also followed by the official steps to request"data"callback processing to capture error information
Reference link: http://blog. Csdn. net/withings/article/details/71331726.Https://segmentfault. com/a/1190000006099651.end



Copyright © 2011 Dowemo All rights reserved.    Creative Commons   AboutUs