Article: Zhijun (Hujiang Web Front-end)

This article is original, please indicate the author and source

In React Native development, we are skilled in sending a request to the server by using JavaScript. However, the process of processing this request is actually different from the process of processing requests sent in Web applications. The target for processing this request is not the browser, but the native operating system embedded in the application.

React Native requests are processed in two parts: the JavaScript runtime environment and the Native (i.e. Native Android and IOS) runtime environment embedded with JavaScript. React Native has three built-in ways to send network requests: FETCH, XMLHttpRequest, and WebSocket. However, the React Native operating environment is different from that of Web applications, so custom functions need to be used in the Native application layer to expand the runtime environment to handle network requests sent by JavaScript.

Request sending method and process

XHR
Fetch
Websocket
React Native

The XMLHttpRequest (XHR)

In React Native, XMLHttpRequest (XHR) consists of two parts: a front-end and a back-end. The front end is responsible for interacting with JavaScript, and the back end is responsible for converting the requests sent by JavaScript into the native system’s own requests on the original console.

The backend is actually a unified API layer that abstracts from the top of the native platform, allowing the JavaScript layer to call the network modules of the original system. For example, the built-in URLSession module in IOS and the OKHTTP module in Android.

Fetch

In modern Web browsers, FetchAPI provides much of the same functionality as XHR, but Fetch provides a simpler and more efficient way to Fetch resources asynchronously across a network, while manipulating Request and Response objects to reuse requests.

However, in React Native, in order to accommodate the differences between the two platforms, Fetch Polyfill, which relies on XMLHttpRequest, is used to implement the request object. This means that we can’t use the React Native object like the Fetch object in the practical Web platform. For example, using this object to send binary data. Of course, third-party libraries such as react-native-fetch-blob can be used to achieve corresponding functions.

Websocket

Websocket, as a new communication protocol, uses full duplex communication mode to communicate with the server network technology.

In React Native, the Websocket is not a separate request. Like XMLHttpRequest (XHR), the Websocket consists of two parts: a front-end and a back-end. The front end is responsible for interacting with JavaScript, and the back end is responsible for converting the requests sent by JavaScript into the native system’s own requests on the original console. In IOS, NSStream developed by myself is used, while in Android system, OKHTTP module is used.

Check network requests in React Native

In React Native, you can use the Sources panel of Chrome Developer Tools (CDT) to debug javascript code, including breakpoints, output information, breakpoint debugging, and all the necessary javascript debugging information. However, the only thing missing is trace debugging of network requests. There is no way to view information about the application’s Network requests through the Network panel in the CDT, as there is in Web development.

Debug network requests using proxies

Although there is no way to view the application’s network requests through CDT, you can set up proxies using software such as Fiddler, CharlesProxy, and Wireshark to view, track, and debug network requests. Fiddler is used as the proxy.

  1. To set up Fiddler’s proxy port, open Filddler > Tool > Options > Connects and fill in the port number.

  2. Set the proxy on the debug machine or in the Android or IOS emulator: Find the network Settings on the debug machine and set the proxy address of the currently connected WIFI

  3. Refresh the app to view network requests in Fiddler (tip: right click and open in a new TAB to view clear images):

In the proxy application, we can view the network information related to request headers, return headers, return results, and so on. Of course, you can intercept the request based on the relevant proxy software, reset it and send it.

useReactotronDebug the network

Above through setting the proxy way to view and track network requests, although powerful, but the actual operation is somewhat difficult, the cost is relatively high. By using Reactotron, debugging configuration information can be integrated into the application, facilitating the same debugging configuration in different development environments and saving development configuration costs.

Reactotron consists of two parts, one is for debugging applications and the other is for debugging configurations.

  1. Debug applications are available for each operating systemGUI Installation Version. Of course, you can use the command line if you preferNPMThe installationreactotron-cli
npm install -g reactotron-cli
Copy the code

  1. Set the debug configuration:
Install 'reactotron-react-native' in your 'React Native' app ` ``` NPM I --save-dev reactotron-react-native 'then add configuration files to your' React Native 'app to customize the debug content:  ``` import Reactotron, { trackGlobalErrors, openInEditor, overlay, asyncStorage, networking } from 'reactotron-react-native' Reactotron .configure({ name: Use (trackGlobalErrors()) // Sets listening for global errors. Use (openInEditor()) // Sets opening of errors in the editor. Use (overlay()) // Use (asyncStorage()) // Set up asynchronous storage debugging. Use (networking()) // Set up network debugging. Connect () // Connect applications (must) Then introduce this configuration file in the entry file of your application. Then restart the application. Of course, you can also use regular expressions to filter the requested 'contentType' and the requested 'URL' to be ignored as follows: use(networking({ignoreContentTypes: / ^ (image) \ /. * $/, / / set reactotron file types to ignore ignoreUrls: / / / (logs | symbolicate) $/, / / set reactotron to ignore the url of the request path})) ` ` `! [reactotron set] (https://raw.githubusercontent.com/yandan66/blogs/master/source/_posts/20171124/reactotron_02.png)! [reactotron set] (https://raw.githubusercontent.com/yandan66/blogs/master/source/_posts/20171124/reactotron_03.png)! [reactotron results] (HTTP: / / https://gitlab.yeshj.com/hujiang-f2e/fun-book/raw/5f6236238c0e51a085d3be32b349436c5e3dad73/%E9%97%A8%E6%8 8%B7%E7%BA%BF/image/ezgif.com-resize.gif)Copy the code

Reactotron debugging the network is just one of its features, but there are many more. Check out his documentation if you’re interested.

Debug the network using the Chrome Developer Tools Web panel

React Native exposed by default in the interface, it is not directly in the Chrome Developer Tools check method of network request, view the RN source Libraries/Core/InitializeCore js, comments:

Sets an object’s property. If a property exists with the same name, this will replace it but maintain its descriptor configuration. By default, the property will replaced with a lazy getter. * The original property value will be preserved as original[PropertyName] so that, if necessary, it can be restored. For example, if you want to route network requests through DevTools (to trace them): * global.XMLHttpRequest = global.originalXMLHttpRequest; * @ see github.com/facebook/re…

Specific implementation in xhrInterceptor.js. The originalXMLHttpRequest has been rewritten to originalXMLHttpRequest, so to display a network in Chrome you simply replace XMLHttpRequest with originalXMLHttpRequest. In the entry file set:

if (__DEV__) {
  GLOBAL.XMLHttpRequest = GLOBAL.originalXMLHttpRequest || GLOBAL.XMLHttpRequest
}
Copy the code

Of course, this can lead to CORS, and Chrome limits cross-domain requests. Either the back end works to remove the limit, or use the allow-Control-Allow-Origin: * plugin.

React Native Sends binary data.

The underlying Fetch object in React Native uses XHR implementation, which limits the ability to send binary data. React Native provides a number of ways to solve this problem, such as converting binaries to Base64 strings or using a third-party library called React-native fetch-blob. But it doesn’t solve the problem at the bottom.

Convert binary to base64 send

Until now React Native couldn’t send unserialized data, so base64-encoded strings were a good choice for sending binary data.

For example, if you download an image from the server (note: not from the server via a URL), the request goes through the JavaScript thread, through the React Native bridge, and finally through the Native system’s network module to the server. The server returns a Base64 encoded image. Upon receiving the returned string, the JavaScript thread allocates memory. React Native calls the corresponding Native module to render the image. But the main thing is that this approach creates a classic performance problem — memory leaks.

There are a number of performance issues associated with transferring binaries through Base64 encoding, most of which are listed in this article and their solutions.

The various methods used to send binary files have various problems, and the ultimate solution is that the corresponding standard can implement binary transmission. Currently, WebSocket already supports binary transport. The React Native layer also supports the WebSocket protocol for transferring binary files, but the network modules of the React Native platform do not support it yet.

conclusion

React Native development is a great experience, but due to platform differences and standards, there are some compromises. With that comes the question of performance and efficiency. In addition, the adoption of development, performance and user experience and native applications still have a certain gap. However, being able to integrate React Native into a Native application would greatly improve development efficiency.

reference

Network layer in React Native

Reactotron introduction

reactotron

Reactotron on React Native

Translation project Master:

1. Dry goods | Everyone is the Master of translation project

2. IKcamp produces a total of 5 chapters and 16 sections of wechat mini program teaching (video included)

3. Began to free serial ~ 2 more per week, a total of 11 iKcamp lesson | based on Koa2 structures, the Node. Js combat (video) | project teaching syllabus is introduced


In 2019, iKcamp’s original new book Koa and Node.js Development Actual Combat has been sold on JD.com, Tmall, Amazon and Dangdang!