The applet wx.request() method

Initiates an HTTPS network request.

parameter

attribute type The default value mandatory instructions Minimum version
url string is Developer server interface address
data string/object/ArrayBuffer no Requested parameters
header Object no Set the requested header. Referer cannot be set in the header.

content-typeThe default isapplication/json
method string GET no HTTP request methods
dataType string json no The format of the data returned
responseType string text no The data type of the response 1.7.0
success function no The interface called the callback function successfully
fail function no Interface failed to invoke the callback function
complete function no Callback function at the end of an interface call (executed on success and failure)

The success callback function returns data data, statusCode, and header

File directory

There are so many request interfaces for a project that we can’t write urls to every file request interface and this is going to be a problem so we’re going to create a file write request interface path as shown here

Method of use

1. API entry file

The API entry file is defined firstlet url = "https://baidu.com";
export default url;
Copy the code

2. Config. js Sets the requested URL

Var API_url = require('.. /apientry/index.js');
var config = {
	api: api_url.default
}
module.exports = {
	ROOT_API: config.api,
}
Copy the code

Domain names are recorded in a special file to facilitate switching to a formal, testing, local environment.

3. Introduce URL and splice the interface given by background

// import the URL and concatenate the interface import {ROOT_API} from'./config';
const hApi = {
    homeInfo: ROOT_API.concat('/homeInfo'} module.exports = hApi;Copy the code

Use a special file to record the interface of the background so that it can be convenient to change the interface, unified modification of the file can be

4. Wrap the wx.request() method

import {homeInfo} './resource.js'; Index.js wraps the wx.request() method var wxRequest = (URL, data = {}, method ='POST') = > {return new Promise(function(resolve, reject) { wx.request({ url, method, data: data,//getObj(data), header: {}, success: (res) => { console.log(res) resolve(res.data) }, fail: (data) => { reject(data) }, complete: (data) => { } }) }) }; OK module.exports = {homeInfo (data){encapsulate the background interface into a method that is called each timereturnwxRequest(homeInfo, data); Var wxRequest = () => {return} is equivalent to var wxRequest =function wxRequest() {returnVar wxRequest = () => ()Copy the code

5. Use method in the page

import {homeInfo} from '@/api/index.js';
async getHomeInfo () {
    let params = {}
    let res = awiat homeInfo (params)
    ...
}
Copy the code

At the end

So that’s the whole process and I welcome your suggestions to learn from each other