1. The introduction of the fetch

React Native officially recommends using the Fetch API. Official document: React Native Network request official document

Structure of 2.

  • HTTP. Js Fetch GET POST encapsulation
  • Api.js where all requests are stored

3. Code

http.js

let common_url = 'https://xlite.kedacom.com/xlite/api'; // The requested URL
let header = {
    "Content-Type": "application/x-www-form-urlencoded"."Cache-Control": "no-cache".// "accesstoken": token // The token returned after the user logs in. Some interfaces involving user data need to add the token to the header
};

const http = {
    get(url, params) {
        if (params) {
            let paramsArray = [];
            // Concatenate parameters
            Object.keys(params).forEach(key= > paramsArray.push(key + '=' + params[key]))
            if (url.search(/ \? /) = = =- 1) {
                url += '? ' + paramsArray.join('&')}else {
                url += '&' + paramsArray.join('&')}}return new Promise(function (resolve, reject) {
            fetch(common_url + url)
                .then((response) = > response.json()
             // Convert the returned data to JSON, or text(), otherwise the returned data cannot be seen and must be called back
                 )        
                .then((responseData) = > {
                    resolve(responseData);
                })
                .catch((err) = > {
                    console.log("err:",err)
                    reject(err);
                });
        });
    },
    post(url, params) {
        return new Promise(function (resolve, reject) {
            fetch(common_url + url, {
                method: 'POST'.headers: header,
                body: JSON.stringify(params)   The //body argument, which usually needs to be converted to a string before the server can parse it
            }).then((response) = > response.json())
                .then((responseData) = > {
                    console.log('res:', url, responseData);   // Network request successfully returned data
                    resolve(responseData);
                })
                .catch((err) = > {
                    console.log('err:', url, err);   // Data returned from network request failurereject(err); }); }); }};/ / export
export default http;
Copy the code

Encapsulation of all apis: api.js

Typically we wrap all API requests into one file

import http from './http';
// Encapsulate the promise
function to(promise){
    return promise
    .then(data= > {
      return [null, data];
    })
    .catch(err= > [err]);
}

const httpApi={	
	/ / the login request
	async login(params) {
		const url = '/userManage/login';
		const [err, res] = await to(http.get(url, params));
		if (err) {
            // The request failed
			return Object.assign(err, {
				status: "406".description: err.errMsg
			}, true);
		}
        // The request succeeded
		return res;
	},
    / / logout request
    async logout(params) {
		const url = '/userManage/logout';
		const [err, res] = await to(http.get(url, params));
		if (err) {
			return Object.assign(err, {
				status: "406".description: err.errMsg
			}, true);
		}
		return res;
	},
    // Other business requests.....
}
export default httpApi;
Copy the code
Next we call it from the login page login.js
//1. Import api.js first
import httpApi from '.. /utils/api';

// The body of a login button method
 async toLogin() {
     let params = {
          username: "username".password: "password"};//2. Call the request interface and pass in the parameters
     let res = await httpApi.login(params);
     
     // Some operations to request reply, which are customized according to your salesman needs and interfaces
     console.log(res)

    }

Copy the code