Call api interface

Posted by phpisawesome on Sat, 05 Mar 2022 16:18:27 +0100

How do we usually call the interface? In Vue, we usually call the interface through the library of axios, but when developing in uniapp, we need to borrow the library of uniapp for development. Next, let's explore it together.

I uni.request(OBJECT)

Function: send network request

Description of OBJECT parameters:

1.url

Type: String

Required: Yes

Default: None

Description: developer server interface address

2.data

Type: Object/String/ArrayBuffer

Required: Yes

Default: None

explain; Requested parameters

3.header

Type: Object

Required: no

Default value; nothing

Note: set the header of the request. Referer cannot be set in the header

Description of platform differences: app and H5 end will automatically bring cookie s, and H5 end cannot be modified manually

4.method

Type: String

Required: no

Default: GET

5.timeout

Type: Number

Required: no

Default value: over time, in ms

6.dataType

Type: String

Required: no

Default: json

Note: if it is set to json, it will try to json the returned data once parse

7.responseType

Type: String

Required: no

Default: text

Description: set the data type of the response. Legal values: text,arraybuffer

8.sslVerify

Type: Boolean

Required: no

Default value: true

Description: validate ssl certificate

9.success

Type: Function

Required: no

Default: None

Note: the callback function successfully returned by the developer server is received

10.fail

Type: Function

Required: no

Default: None

Description: failed callback function of interface call

11.complete

Type: Function

Required: no

Default: None

Description: callback function at the end of interface call (it will be executed if the call succeeds or fails)

II method valid value

Note: the valid values of method must be in uppercase. The valid values of method supported by each platform are different. See the following table for details.

III success return parameter description

data description

The final data sent to the server is of String type. If the incoming data is not of String type, it will be converted to String. The conversion rules are as follows:

  • For the GET method, the data is converted to query string. For example, {name: 'name', age: 18} after conversion, the result is name = name & age = 18.
  • JSON serialization will be performed for the data with the method of "POST" and the header['content-type '] is "application/json".
  • For the data of "POST" method and "header ['content type '] is" application/x-www-form-urlencoded ", the data will be converted into query string

IV Send a successful request using uniapp

I use mockfast to simulate a server to send requests.

1. Prepare a mock to simulate the data

 

2. Bind a click event to the button and get the data through the success ful callback

code:

<template>
	<view class="">
 <button type="warn" @click="fn">Click send request</button>	
	 {{aa}}
	</view>
 

</template>

<script>
export default {
 data () {
    return {
      aa:''
    }
  },
  methods: {
	  fn(){
		uni.request({
		    url: 'https://www.fastmock.site/mock/010910d86b5019f8016429f50c680e58/api/test ', / / it is only an example, not a real interface address.
		    success: (res) => {
		       this.aa=res.data.name

		    }
		});
		
		}
     }

}
</script>

<style>
	
</style>

Illustration:

 

 

V Callback after fail

1. Modify the url address

Printed results

 

 

Vi Test complete

Description: callback function at the end of interface call (it will be executed if the call succeeds or fails)

1. After interface call fails

 

  

2. The interface call was successfully executed

 

 

3. For application scenarios

Some corresponding operations after the request is completed

VII Encapsulate a uni request

For Uni Some common parameters of request are simply encapsulated to reduce repetitive data request code. Facilitate global call.

Steps:

1. First create two folders unils and common in the directory

utils is used to store tool classes, and common is used to place common methods

Then create a request in utils JS is used to place Uni The request method of request is simply encapsulated

2.requset.js code (in utils folder)

import operate from '../common/operate.js'
// Please refer to the official website for details of vuex https://uniapp.dcloud.io/vue-vuex
import store from '../store/index.js'  

export default class Request {
    http(param) {
        // Request parameters
        var url = param.url,
            method = param.method,
            header = {},
            data = param.data || {},
            token = param.token || "",
            hideLoading = param.hideLoading || false;

        //Splice complete request address
        var requestUrl = operate.api + url;
       //Splicing complete request address (switching according to environment)
       // var requestUrl = operate.api() + url;

        //Request method: GET or POST(POST needs to be configured)
        // header: {'content-type' : "application/x-www-form-urlencoded"},)
        if (method) {
            method = method.toUpperCase(); //Change lowercase to uppercase
            if (method == "POST") {
                header = {
                    'content-type': "application/x-www-form-urlencoded"
                };
            } else {
                header = {
                    'content-type': "application/json"
                };
            }
        }

        //Loading ring
        if (!hideLoading) {
            uni.showLoading({
                title: 'Loading...'
            });
        }

        // Return promise
        return new Promise((resolve, reject) => {
            // request
            uni.request({
                url: requestUrl,
                data: data,
                method: method,
                header: header,
                success: (res) => {
                    // Determine whether the request api format is correct
                    if (res.statusCode && res.statusCode != 200) {
                        uni.showToast({
                            title: "api error" + res.errMsg,
                            icon: 'none'
                        });
                        return;
                    }
                    // Throw the result
                    resolve(res.data)
                },
                //request was aborted
                fail: (e) => {
                    uni.showToast({
                        title: "" + e.data.msg,
                        icon: 'none'
                    });
                    resolve(e.data);
                },
                //Request complete
                complete() {
                    //Hide loading
                    if (!hideLoading) {
                        uni.hideLoading();
                    }
                    resolve();
                    return;
                }
            })
        })
    }
}

3. Create operate. In common js

1.operate.js is used to place the api address of the request interface

export default {
    //Interface
    api: "http://192.168.208.126:8080",
}

Switch interface address according to applet environment

export default {
	//Interface
	api: function() {
	    let version = wx.getAccountInfoSync().miniProgram.envVersion;
	    switch (version) {
		case "develop": //Developer Preview 
			return "https://www.baidu.com/"
			break;
		case 'trial': //Experience version
			return "https://www.baidu.com/"
			break;
		case 'release': //Official edition
			return "https://www.baidu.com/"
			break;
		default: //Unknown, call the official version by default
			return "http://www.baidu.com/"
			break;
	}
}

4. Usage method 1 (Global request)

Create api folder in the following directory: create api js

api.js is used to call our encapsulated Uni Request, and unified management request interface, in subsequent development only need to call api. in the page JS

import Request from '@/utils/requset.js'
let request = new Request().http

//Global definition request header
export default {
    // Request style
    classifyLeft: function(data) {
        return request({
            url: "/category/list", //Request header
            method: "GET", //Request mode
            data: data, //Request data
        })
    },
}
/*
Request style:
    Custom Name: function(data){
        return request({
            url: "/banner", //Request header
            method: "GET", //Request mode 
            data: data,    //Request data
            token: token, // Transmissible  
            hideLoading: false, //Load style
        })
    },
*/

api.js can be called in main Global calls in JS can also be invoked in the required pages, depending on the actual situation to decide whether to make global calls. Only global calls are described below

In Mian JS js

1. stay main.js Introduced in api.js
        import api from '@/common/api.js'
        Vue.prototype.$api = api
2. Call in page
        //No parameters
        this.$api.sendRequest().then((res) => {
            console.log(res);
        })
        //Chuan Shen
        this.$api.sendRequest({parameter}).then((res) => {
            console.log(res);
        })

5. Usage method 2 (introduced separately on the page)

user.js is used to call our encapsulated Uni Request, and unified management request interface, in subsequent development only need to call user. in the page JS

import Request from '@/utils/requset.js'
import operate from '@/common/operate.js'
let request = new Request().http

// On demand incoming request header
export const getUserInfo= function(data) {    
    return request({
	url: "order/user ",		
        method: "POST",
	data: data,
	token: operate.isToken()
    })
}

Use in page

//introduce
import {
    getUserInfo
} from '@/api/user.js'

//Put into life cycle
init() {
    //User information
    getUserInfo().then((res) => {
	console.log(res);
    })
},

Packaging reference of interface: https://juejin.cn/post/7023983465892675614

Topics: Javascript Front-end Vue.js uni-app