React Native uses the sample code of Fetch to send network requests, reactfetch

Source: Internet
Author: User

React Native uses the sample code of Fetch to send network requests, reactfetch

HTTP requests are usually used in projects to access the network. HTTP (HTTPS) requests are generally divided into "GET", "PUT", "POST", and "DELETE ", if not specified, the default value is GET.

In projects, we usually use GET and POST request methods. We usually use POST request methods to submit such requests for forms with parameters.

To send an HTTP request, we need to use the Fetch API provided by React Native for implementation. To get content from any address, simply pass the URL as a parameter to the fetch method.

GET

If you want to use the GET method to request data and convert it to JSON, you can use the following code:

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

Use the above request to convert the returned Response into a JSON Object, and then retrieve the movies field in the json Object. At the same time, if an Error occurs, such as a network failure or an access connection Error, it will be caught. Under normal circumstances, we can get the following results:

{ "title": "The Basics - Networking", "description": "Your app fetched this from a remote endpoint!", "movies": [  { "title": "Star Wars", "releaseYear": "1977"},  { "title": "Back to the Future", "releaseYear": "1985"},  { "title": "The Matrix", "releaseYear": "1999"},  { "title": "Inception", "releaseYear": "2010"},  { "title": "Interstellar", "releaseYear": "2014"} ]}

POST (1)

Of course, the above is the most basic GET request, and Fetch has another optional second parameter, which can be used to customize some parameters of the HTTP request. You can specify the Headers parameter, POST Method, data submission, and so on. The Fetch API also supports custom Headers, change Method, and add Body.

let url = "http://www.yousite.com/xxxx.ashx” let params = {"name":"admin","password":"admin"}; fetch(url, { method: 'POST', headers: {  'Accept': 'application/json',  'Content-Type': 'application/json', }, body: JSON.stringify(params)})

A basic POST request is constructed above, with Headers: Accept and Content-Type added and Body added.

POST (2)

let url = "http://www.yousite.com/xxxx.ashx”; let params = "username=admin&password=admin”; fetch(url, {  method: 'POST',  headers: {    'Content-Type': 'application/x-www-form-urlencoded'  },  body: params,}).then((response) => {  if (response.ok) {    return response.json();  }}).then((json) => {  console.log(json)}).catch((error) => {  console.error(error);});

POST (3) Recommendation

The above two methods allow us to send POST requests. Of course, this method is also recommended.

If your server cannot identify the above POST data format, you can try the traditional form format, for example:

Let REQUEST_URL = 'HTTP: // www.yousite.com/xxxx.ashx'#// 'first, we need to create a FormData file to store the request parameter 'let parameters = new FormData (); parameters. append ("mt", "30013"); parameters. append ("pg", "1"); parameters. append ('ps', '20'); fetch (REQUEST_URL, {method: 'post', body: parameters }). then (result) => {if (result. OK) {console. log (result) result. json (). then (obj) => {console. log (obj )})}}). catch (error) => {console. log (error) Alert. alert ('error ')})

Another advantage of this method is that byte streams can be directly transmitted in FormData to upload images. The Code is as follows:

uploadImage(){  let formData = new FormData();  let file = {uri: uri, type: 'multipart/form-data', name: 'a.jpg'};  formData.append("images",file);  fetch(url,{   method:'POST',   headers:{     'Content-Type':'multipart/form-data',   },   body:formData,  })  .then((response) => response.text() )  .then((responseData)=>{   console.log('responseData',responseData);  })  .catch((error)=>{console.error('error',error)}); }

Processing Server Response Data

The example above demonstrates how to initiate a request. In many cases, you also need to process the server response data.
A network request is a kind of asynchronous operation. The Fetch method returns a Promise. This mode simplifies the code in the asynchronous mode. For details about Promise, see Promise.

To process the data returned by the server, we have processed the data in the second and third POST requests above. For specific code, refer to the above implementation code.

By default, iOS blocks all non-https requests. If the requested interface is http, you must first add an App Transport Security exception.

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.