Home > Web Front-end > JS Tutorial > How to use Fetch to send network requests in React Native

How to use Fetch to send network requests in React Native

亚连
Release: 2018-06-22 18:12:47
Original
1622 people have browsed it

This article mainly introduces the sample code of React Native using Fetch to send network requests. It has certain reference value. Interested friends can refer to it

We often use HTTP in our projects Request to access the network. HTTP (HTTPS) requests are usually divided into "GET", "PUT", "POST", and "DELETE". If not specified, the default is GET request.

In projects, we generally use two request methods: GET and POST. For submitting such requests in forms with parameters, we usually use the POST request method.

In order to make HTTP requests, 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 (the word fetch itself means fetch

GET

If you want to request data through the GET method and convert it into JSON, you can do it through 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);
   });
Copy after login

Convert the returned Response into a JSON Object through the above request, and then take out the movies field in the JSON Object .At the same time, if an Error occurs, such as network failure or access connection error, etc., it will be .catched. 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"}
 ]
}
Copy after login

POST (1)

Of course, the above is the most basic GET request. Fetch also has an optional second parameter, which can be used to customize some parameters of the HTTP request. You can specify the Headers parameters, or specify the use of the POST method, or Or submit data, etc.: Fetch API also supports customizing Headers, changing Method, adding Body, etc.

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)
})
Copy after login

The above constructs a basic POST request and adds its own Headers: Accept and Content-Type. Added Body.

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);
});
Copy after login

POST (3) Recommendation

Through the above two methods, We have another way to send a POST request, and of course this method is also recommended.

If your server cannot recognize the above POST data format, you can try the traditional form format. The example is as follows:

let REQUEST_URL = 'http://www.yousite.com/xxxx.ashx';

// `首先我们需要自己创建一个FormData,来存请求参数`

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')
})
Copy after login

Another advantage of recommending this method is that you can directly pass the byte stream in FormData to implement the function of uploading pictures. 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)}); 

}
Copy after login

Process the server's response data

The above example demonstrates how to initiate a request. In many cases, you also need to process the data returned by the server.
Network requests are naturally an asynchronous operation, and the Fetch method will return a Promise. This mode can simplify asynchronous style code. Regarding Promise, please refer to: Promise

Processing data returned by the server. We have implemented data processing in the second and third POST requests above. For specific code, refer to the implementation code above.

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

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

How to implement flux on knockoutjs

How to implement seamless scrolling components using vue

About the difficulty of JavaScript array operation (detailed tutorial)

How to implement the like function in the WeChat applet

The above is the detailed content of How to use Fetch to send network requests in React Native. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template