This article mainly introduces the details of the http request encapsulation of applets and the relevant information about the instance code. For more information, see
Small program http request encapsulation
Sample code
Wx. request ({url: 'Test. php ', // only for example, not the actual interface address data: {x: '', y:''}, method: 'post', header: {'content-type': 'application/json'}, success: function (res) {console. log (res. data)}, fail: function (res) {fail (res );}})
The above is the basic http request code of the applet. in actual code, if this is complicated to write, we will encapsulate it.
What do we pay more attention to in the code?
1. request parameters and access interfaces
2. GET/POST... request method
3. Unified request parameter processing (such as encryption and setting public parameters ...)
4. data returned after a successful request (for example, decryption and extraction of data from the logic layer)
5. request failure feedback
What do we not care about?
1. Request url (usually fixed configuration somewhere)
2. perform different request parameters based on different interface rules (for example, parameter encryption)
...
Let's implement code
Network. js
Var API_URL = 'http: // localhost/loverule/api. php 'Var requestHandler = {params :{}, success: function (res) {// success}, fail: function () {// fail },} // GET request function GET (requestHandler) {request ('GET', requestHandler)} // POST request function POST (requestHandler) {request ('post', requestHandler )} function request (method, requestHandler) {// Note: you can process var params = requestHandler for params encryption. params; wx. request ({url: API_URL, data: params, method: method, // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT // header :{}, // Set the request header success: function (res) {// Note: You can decrypt parameters and process requestHandler. success (res)}, fail: function () {requestHandler. fail ()}, complete: function () {// complete})} module. exports = {GET: GET, POST: POST}
1. call in the page (take the GET request as an example)
// Import js var network = require (".. /.. /utils/network. js ") // write the parameter var params = new Object () params. api_name = "api_user_login" params. account = "hanqing" params. password = "123456" // initiate the request network. GET ({params: params, success: function (res) {console. log (res) // Obtain the decrypted data and perform code logic}, fail: function () {// Logic after failure },})
Thank you for reading this article. I hope it will help you. thank you for your support for this site!
For more details about http request encapsulation of applets and related articles on instance code, please follow the PHP Chinese network!