Network request + WebSocket based on Node.js

 

Table of contents

foreword

Network access configuration

1. Configuration process

Precautions

usage restrictions

Network Request Details API

wx.request request data API

​edit

wx.uploadFile file upload API

wx.downloadFile file download API

WebSocket Session API

Node.js based WebSocket

Why WebSocket connections can achieve full-duplex communication but HTTP connections can't?

At present, the mainstream browsers that support WebSocket are as follows:

 Brief introduction to WebSocket


foreword

If the applet dynamically renders the page, it needs to obtain data from the background server interface, and cannot directly write the data in the page or business logic layer. Such data is static. Dynamic data needs to be obtained by calling the interface to initiate a network request, returning the data through the API, and then rendering it to the page view to achieve the effect of displaying the page.

Network access configuration

 

Before the applet initiates a network request, it needs to access the configuration of the domain name on the WeChat public platform. The applet only allows access to the configured domain name, including the domain name of ordinary HTTPS request (wx.request), upload file (wx.uploadFile), download file (wx.downloadFile) and WebSocket communication (wx.connectSocket)!

        Note: As of base library 2.4.0, network requests allow communication with LAN IP, but be careful not to allow communication with native IP. Starting from the base library 2.7.0, the applet provides UDP communication (wx.createUDPSocket), which only allows communication with non-native IPs in the same local area network.

1. Configuration process

 

Log in on the homepage of the WeChat public platform, and configure it in "Development" > "Development Settings" > "Server Domain Name" in the backend of the Mini Program (you need to scan the code with the registered WeChat to confirm your identity)

 If the domain name is not configured for direct access, the system will prompt an error message!

Precautions

1. The domain name only supports https (wx.reauest, wx.uplosdFile, wx.downloadFile) and wss (wx.connect-Socket) protocols.

2. The domain name cannot use an IP address (except the local area network IP of the applet) or localhost.

3. You can configure the port, such as https://xxxxx.com:xxxx, but after configuration, you can only initiate a request to https://xxxxx.com:xxxx. If you send a request to https://xxxxx.com, https://xxxxx URLs such as .com:yyyy will fail to send requests.

4. If the port is not configured, such as https://xxxxx.com, the requested URL cannot contain the port, even if it is the default 443 port, if the request is sent to https://xxxxx.com:443, it will fail.

5. The domain name must go through ICP filing.

6. For security reasons, api.weixin.qq.com cannot be configured with a server domain name, and related APIs cannot be called within the applet. The developer should save the AppSecret to the background server, use the getAccessToken interface to obtain the access_token through the server, and call the relevant API.

7. For each interface, up to 20 domain names can be configured respectively.

8. The default timeout period and the maximum timeout period for network requests are 60s. The timeout period can be configured through networktimeout in the app.json file or game.json file.

usage restrictions

 

Network access also has usage restrictions, including network request settings, concurrency limit settings, timeout settings, encoding settings and other usage restrictions.

1. The request source referer header of the network request cannot be set. The format is fixed as https://servicewechat.com/{appid}/{version}/page-frame.html, where {appid} is the appid of the applet, {version} is the version number of the applet, and the version number is 0 Indicates the development version, the trial version and the audit version, the version number is devtools, which is the developer tool, and the rest are the official version number.

2. The maximum concurrent limit of wx.reauest, wx.uploadFile and wx.downloadFile is 10.

3. The maximum concurrent limit of wx.connectSockt is 5.

4. After the applet runs in the background, if the network request does not end within 5s, the error message fail interrupted will be called back; before returning to the foreground, the network request interface will not be able to be called.

5. It is recommended that the server return value use UTF-8 encoding. For non-UTF-8 encoding, the applet will try to convert, but the conversion may fail.

6. The applet will automatically filter the BOM header (only one BOM header is filtered).

7. As long as the return value from the server is successfully received, no matter what the return status code (statusCode) is, it will enter the success (success) callback. Here you can judge the return value according to your own business logic.

Network Request Details API

 

wx.request request data API

 

wx.request is an API used to request server data. It initiates an HTTPS request to obtain data from the backend server interface. wx.request(Object object) has an Object object parameter.

When a wx.request request is initiated, the system also creates a RequestTask object, which provides the following three methods.

1.RequestTask.abort() interrupt request task.

2.RequestTask.onHeaderReceived(function callback) listens for HTTP Response Header events.

3.RequestTask.offHeaderReceived(function callback) cancels listening to the HTTP Response Header event .

We have used https://www.toutiao.com as an example to implement the code:

// pages/index/index.js
Page({

onLoad:function(){
  var requestTask = wx.request({
    url: 'https://www.toutiao.com',
    data:{
      provinceld:'1'
    },
    method:'GET',
    success:function(res){
      console.log(res)
    },
    fail:function(err){

    },
    complete:function(){

    }
  });
  //监听HTTP Response Header事件
  requestTask.onHeadersReceived(function(res){
    console.log("-----------监听HTTP Response Header事件----------");
    console.log(res)
  })
  //取消监听HTTP Response Header事件
  requestTask.offHeadersReceived(function(res){
    console.log("------------取消HTTP Response Header事件----------");
    // console.log(res)
  })
  
},

})

When the data is sent to the server after the request is successful, the data is of string type. If the incoming data is not of dstring type, it will be converted to string. The conversion rules are as follows.

1. For data whose header['Content-Type'] is 'Application/json', JSON serialization will be performed on the data.

2. For the data whose header['Content-Type'] is 'Application/x-www-form-urlencoded', the data will be converted into query string(encodeURlComponent(k)=encodeURlComponent(v)&encodeURIComponent(k)=encodeURIComponent( v)...).

wx.uploadFile file upload API

 

The wx.uploadFile API can upload local resources to the server. The client initiates an HTTPS POST request.

When a wx.uploadFile request is initiated, the system also creates an UploadTask object, which provides the following five methods:

1.UploadTask.abort() interrupt request task.

2.UploadTask.onHeadersReceived(function callback) listens for HTTP Response Header events.

3.UploadTask.offHeadersReceived(function callback) cancels listening to the HTTP Response Header event.

4.UploadTask.onProgressUpdate(function callback) monitors the upload progress change event.

5.UploadTask.offProgressUpdate(function callback) cancels monitoring the upload progress change event.

uploadTask is an object created by wx.uploadFile. It can use uploadTask.abort() to interrupt the request task and stop the atmospheric network request; use uploadTask.onHeaderReceived(function callback) to listen to the HTTP Response Header event, which will be completed earlier than the request completion event. ; uploadTask.offHeaderReceived(function callback) cancels monitoring of HTTP Response Header events; use uploadTask.onProgressUpdate(function callback) to monitor upload progress change events; use uploadTask.offProgressUpdate(function callback) to cancel monitoring upload progress change events.

wx.downloadFile file download API

 

wx.uploadFile is the API for uploading files, and wx.downloadFile is the API for downloading files. They are just the opposite. wx.downloadFile is an HTTPS GET request directly initiated by the client, and the data obtained from the server returns the local temporary path of the file, word The maximum file size allowed for download is 50MB, and it is downloaded to the applet client locally.

An object created by the DownloadTask object wx.downloadFile, which can monitor the download progress change event and cancel the download task object. The DownloadTask object provides the following methods:

1.DownloadTask.abort() Terminal download task.

2.DownloadTask.onProgressUpdate(function callback) monitors the download progress change event.

3.DownloadTask.offProgressUpdate(function callback) cancels monitoring download progress change events.

4.DownloadTask.onHeadersReceived(function callback) listens to the HTTP Response Header event, which will be earlier than the request completion event.

5.DownloadTask. offHeadersReceived(function callback) cancels listening for HTTP Response Header events.

 

The first thing to execute is DownloadTask.onHeadersReceived(function callback) to listen to the HTTP Response Header event , which is executed earlier than the request supervision event; then the thing to execute is DownloadTask.onProgressUpdate(function callback) to listen to the download and progress change events until the download is complete; finally, the file is returned The temporary path, according to the temporary path, the file can be rendered, the file can be rendered to the view or downloaded to the mobile client.

WebSocket Session API

 

WebSocket is actually a multi-party communication interface. When the applet is deployed to the service provider, WebSocket allows multiple mobile phones to access the background server to establish communication!

 

The WebSocket session API is used to create a session connection. After the session connection is created, they can communicate with each other, just like WeChat chat and QQ chat. He will use the following 7 methods:

1.wx.connectSocket(OBJECT) creates a session link.

2.wx.onSocketOpen(CALLBACK) monitors the WebSocket connection open event.

3.wx.onSocketError(CALLBACK) monitors WebSocket errors.

4.wx.sendSocketMessage(OBJECT) sends data.

5.wx.onSocketMessage(CALLBACK) listens for the WebSocket to receive the message event of the server.

6.wx.closeSocket() closes the WebSocket connection.

7.wx.onSocketClose(CALLBACK) listens for WebSocket close.

Note: A WeChat applet can only have one WebSocket connection at the same time. If a WebSocket connection already exists when it is created, the connection will be automatically closed and a WebSocket connection will be re-created.

Node.js based WebSocket

 

WebSocket requires the cooperation of a background program, and the background program can be a Java program under Tomcat or a Node.js program. Simply put, Node.js is JavaScript running on the server side. Node.js is a platform based on the Chrome JavaScript runtime. It is an event-driven I/O server-side JavaScript environment. It is based on Google's V8 engine. Because the V8 engine executes JavaScript very fast, its performance is very good!

WebSocket is a new protocol in HTML5. Its purpose is to establish an unrestricted two-way communication channel between the browser and the server . For example, the server can send messages to the browser at any time. Either party can take the initiative to send a message to the other party.

The HTTP protocol is a request-response protocol. The request must first be sent by the browser to the server before the server can respond to the request and then send the data to the browser. In other words, if the browser does not actively request, the server cannot actively send data to the browser.

WebSocket is not a new protocol, but uses the HTTP protocol to establish a connection. Let's see how a WebSocket connection is created.

This request is different from a normal HTTP request in a few ways:

  1. The address of the GET request is not similar /path/, but ws://the address starting with;
  2. request header Upgrade: websocketand  Connection: Upgradeindicates that this connection will be converted to a WebSocket connection;
  3. Sec-WebSocket-Keyis used to identify this connection, not to encrypt data;
  4. Sec-WebSocket-VersionSpecifies the protocol version of WebSocket.

Why WebSocket connections can achieve full-duplex communication but HTTP connections can't?

 

In fact, the HTTP protocol is built on top of the TCP protocol. The TCP protocol itself realizes full-duplex communication, but the request-response mechanism of the HTTP protocol limits full-duplex communication. After the WebSocket connection is established, it is actually just a simple rule: Next, we will not use the HTTP protocol for communication, and send data directly to each other.

The secure WebSocket connection mechanism is similar to HTTPS:

First, when the browser wss://xxxcreates a WebSocket connection, it will first create a secure connection through HTTPS. Then, the HTTPS connection is upgraded to a WebSocket connection, and the underlying communication is still the secure SSL/TLS protocol.

Obviously, to support WebSocket communication, the browser must support this protocol, so that ws://xxxthe request can be issued.

At present, the mainstream browsers that support WebSocket are as follows:

  • Chrome

  • Firefox
  • IE >= 10
  • Money >= 6
  • Android >= 4.4
  • iOS >= 8

 

 Brief introduction to WebSocket

Since WebSocket is a protocol, how the server implements it depends on the programming language used and the framework itself. The protocols supported by Node.js include the TCP protocol and the HTTP protocol. To support the WebSocket protocol, additional development of the HTTPServer provided by Node.js is required. There are already several stable and reliable WebSocket implementations based on Node.js, we can install and use them directly with npm.

其实wsModules contain both the server side and the client side. wsIt means the WebSocketclient, which is actually the type connectionof the variable passed in by the callback function when the WebSocketServer responds to the event .ws

Guess you like

Origin blog.csdn.net/lbcyllqj/article/details/127467041