Foreword:
The request background interface for method sorting in uni-app. Personal package version and official method.
Official entry:
Package version: see the directory below
1. Create a new folder api, where the interface information is mainly placed
login.js puts the interface method of the login page
import axios from '../util/http'
const Login = {
// 获取验证码
goPhoneCode(params) {
return axios({
method:'get',
url:`/phoneCode`,
params:params
})
},
}
export default Login
index.js registers all interface methods
/**
* api接口的统一出口
*/
import common from './common'
import login from './login'
export default {
common,
login,
}
2. Create a new util folder and create three new files
Cache method encapsulated by auth.js
const TokenKey = 'uni_token';
// 认证令牌
export function getToken() {
return uni.getStorageSync(TokenKey)
}
export function setToken(token) {
return uni.setStorageSync(TokenKey, token)
}
export function removeToken() {
return uni.removeStorageSync(TokenKey)
}
The request interface method encapsulated by http.js
import {getToken,removeToken} from './auth';
import env from './env';
// 封装数据返回成功提示函数------------------------------------------------------
function successState(res) {
let code = res.data.code;
console.log('@return-data:')
console.log(res)
//公共报错提醒
if(code !== 200){
// 非成功状态码弹窗
uni.showToast({
icon: 'none',
duration: 3000,
title: `${res.data.msg}`
});
}
// 登陆失效
if (res.data.code === 403) {
// 清除本地token
removeToken()
// 关闭所有页面返回到登录页
uni.reLaunch({
url: '/pages/login/login'
})
}
console.log('/------http(END)------/')
return res
}
// 封装数据返回失败提示函数------------------------------------------------------
function errorState(err) {
// 请求失败弹窗
uni.showToast({
icon: 'none',
duration: 3000,
title: '服务器错误,请稍后再试'
});
console.log('/------http(END)------/')
}
// 封装axios---------------------------------------------------------------------
function service(options = {}) {
options.url = `${env.baseUrl}${options.url}`;
// 判断本地是否存在token,如果存在则带上请求头
if (getToken()) {
options.header = {
'content-type': 'application/json',
'authorization': `${getToken()}` // 这里是token
};
}
console.log('/------http(START)------/')
console.log('@all-url:')
console.log(options.url)
console.log('@params:')
console.log(options)
return new Promise((resolved, rejected) => {
options.success = (res) => {
successState(res)
resolved(res)
};
options.fail = (err) => {
errorState(err)
rejected(err);
};
uni.request(options);
});
}
export default service;v
env.js public baseurl address and other variables
"use strict";
/**
* appid : 小程序appid
* baseUrl : 服务端域名
*/
export default {
appid: '****',
baseUrl: 'http://***.70.94.135:7001'
}
3. Global configuration in main.js
//接口
import api from './api'
Vue.prototype.$api = api
4. Specific use in the page
mounted() {
this.getLoginCap()
},
methods: {
//获取验证码
getLoginCap(){
let phone = '13519102731'
this.$api.login.goPhoneCode({phone}).then(res=>{
debugger
if(res.data.code == 200){
}
})
}
}
Open the console.log of f12 , you can see the specific address, parameters and return value
Official method: Click me to enter directly
uni.request(OBJECT)
When each Mini Program platform is running, network-related APIs need to be configured with a whitelist of domain names before being used.
OBJECT parameter description
parameter name | Types of | Required | Defaults | illustrate | Platform Difference Description |
---|---|---|---|---|---|
url | String | Yes | Developer server interface address | ||
data | Object/String/ArrayBuffer | no | request parameters | App does not support ArrayBuffer type | |
header | Object | no | Set the header of the request. The Referer cannot be set in the header. | The App and H5 side will automatically bring cookies, and the H5 side cannot be manually modified | |
method | String | no | GET | For valid values, see the description below | |
timeout | Number | no | 60000 | Timeout time, in ms | H5 (HBuilderX 2.9.9+), APP (HBuilderX 2.9.9+), WeChat applet (2.10.0), Alipay applet |
dataType | String | no | json | If set to json, it will try to do a JSON.parse on the returned data | |
responseType | String | no | text | Set the data type of the response. Legal values: text, arraybuffer | Alipay applet does not support |
sslVerify | Boolean | no | true | verify ssl certificate | App Android only supports (HBuilderX 2.3.3+), does not support offline packaging |
withCredentials | Boolean | no | false | Whether to carry credentials (cookies) in cross-domain requests | H5 support only (HBuilderX 2.6.15+) |
firstIpv4 | Boolean | no | false | ipv4 is preferred for DNS resolution | App-Android only supported (HBuilderX 2.8.0+) |
success | Function | no | Receive the callback function successfully returned by the developer server | ||
fail | Function | no | Callback function for interface call failure | ||
complete | Function | no | The callback function of the end of the interface call (the call will be executed if it succeeds or fails) |
method valid values
Note: The valid value of method must be capitalized. The valid value of method supported by each platform is different. For details, see the table below.
method | App | H5 | WeChat applet | Alipay applet | Baidu applet | ByteDance applet, Feishu applet |
---|---|---|---|---|---|---|
GET | √ | √ | √ | √ | √ | √ |
POST | √ | √ | √ | √ | √ | √ |
PUT | √ | √ | √ | x | √ | √ |
DELETE | √ | √ | √ | x | √ | x |
CONNECT | x | √ | √ | x | x | x |
HEAD | x | √ | √ | x | √ | x |
OPTIONS | √ | √ | √ | x | √ | x |
TRACE | x | √ | √ | x | x | x |
success return parameter description
parameter | Types of | illustrate |
---|---|---|
data | Object/String/ArrayBuffer | Data returned by the developer server |
statusCode | Number | The HTTP status code returned by the developer server |
header | Object | The HTTP Response Header returned by the developer server |
cookies | Array.<string> |
Cookies returned by the developer server, formatted as a string array |
data data description
The final data sent to the server is of type String. If the incoming data is not of type String, it will be converted to String. The conversion rules are as follows:
- For
GET
methods, the data is converted to a query string. For example{ name: 'name', age: 18 }
the converted result isname=name&age=18
. - For data that is
POST
method andheader['content-type']
isapplication/json
, JSON serialization is performed. - For data that is
POST
method andheader['content-type']
isapplication/x-www-form-urlencoded
, the data will be converted to a query string.