preface:
Request background interface for method collation in uni app. Personal encapsulated version and official method.
Official entrance:
Package version: see the following table of contents
1. Create a new folder api, which mainly puts the interface information
login.js interface method for putting login page
import axios from '../util/http' const Login = { // Get verification code goPhoneCode(params) { return axios({ method:'get', url:`/phoneCode`, params:params }) }, } export default Login
index.js register all interface methods
/** * api Unified exit of interface */ import common from './common' import login from './login' export default { common, login, }
2. Create a new util folder and create three new files
auth.js encapsulated caching method
const TokenKey = 'uni_token'; // authentication token export function getToken() { return uni.getStorageSync(TokenKey) } export function setToken(token) { return uni.setStorageSync(TokenKey, token) } export function removeToken() { return uni.removeStorageSync(TokenKey) }
http.js encapsulated request interface method
import {getToken,removeToken} from './auth'; import env from './env'; // Function of success prompt returned by encapsulating data------------------------------------------------------ function successState(res) { let code = res.data.code; console.log('@return-data:') console.log(res) //Public error notification if(code !== 200){ // Unsuccessful status code pop-up uni.showToast({ icon: 'none', duration: 3000, title: `${res.data.msg}` }); } // Login failure if (res.data.code === 403) { // Clear local token removeToken() // Close all pages and return to the login page uni.reLaunch({ url: '/pages/login/login' }) } console.log('/------http(END)------/') return res } // Encapsulation data return failure prompt function------------------------------------------------------ function errorState(err) { // Request failed Popup uni.showToast({ icon: 'none', duration: 3000, title: 'Server error,Please try again later' }); console.log('/------http(END)------/') } // Encapsulating axios--------------------------------------------------------------------- function service(options = {}) { options.url = `${env.baseUrl}${options.url}`; // Judge whether there is a token in the local area. If so, bring the request header if (getToken()) { options.header = { 'content-type': 'application/json', 'authorization': `${getToken()}` // This is 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 : Applet appid * baseUrl : Server domain name */ export default { appid: '****', baseUrl: 'http://***.70.94.135:7001' }
3,main. Global configuration in JS
//Interface import api from './api' Vue.prototype.$api = api
4. Specific use in the page
mounted() { this.getLoginCap() }, methods: { //Get verification code getLoginCap(){ let phone = '13519102731' this.$api.login.goPhoneCode({phone}).then(res=>{ debugger if(res.data.code == 200){ } }) } }
Open the console of f12 Log, you can see the specific address, parameters and return values
Official method: I'll go straight in
uni.request(OBJECT)
When each applet platform is running, the network related API needs to configure the domain name white list before use.
OBJECT parameter description
Parameter name
type
Required
Default value
explain
Platform difference description
url
String
yes
Developer server interface address
data
Object/String/ArrayBuffer
no
Requested parameters
App does not support ArrayBuffer type
header
Object
no
Set the header of the request. Referer s cannot be set in the header.
The App and H5 end will automatically bring cookie s, and the H5 end cannot be modified manually
method
String
no
GET
See the description below for the valid values
timeout
Number
no
60000
Timeout in ms
H5(HBuilderX 2.9.9+), APP(HBuilderX 2.9.9+), WeChat applet (2.10.0), Alipay applet.
dataType
String
no
json
If it is set to json, it will try to json the returned data once parse
responseType
String
no
text
Set the data type of the response. Legal values: text, arraybuffer
Alipay applet does not support
sslVerify
Boolean
no
true
Validate ssl certificate
Only App Android supports (HBuilderX 2.3.3 +), and offline packaging is not supported
withCredentials
Boolean
no
false
Whether to carry credentials (cookies) when making cross domain requests
H5 only (HBuilderX 2.6.15 +)
firstIpv4
Boolean
no
false
ipv4 is preferred in DNS resolution
App Android only (HBuilderX 2.8.0 +)
success
Function
no
Received the callback function successfully returned by the developer server
fail
Function
no
Interface call failed callback function
complete
Function
no
Callback function at the end of interface call (both successful and failed calls will be executed)
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.
method
App
H5
Wechat applet
Alipay applet
Baidu applet
Byte beating applet, flying Book 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
type
explain
data
Object/String/ArrayBuffer
Data returned by the developer server
statusCode
Number
HTTP status code returned by the developer server
header
Object
HTTP Response Header returned by the developer server
cookies
Array.<string>
cookies returned by the developer server in the form of string array
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} the result after conversion is name = name & age = 18.
- For the data of POST method and header['content-type '] is application/json, JSON serialization will be performed.
- For POST method data whose header['content-type '] is application/x-www-form-urlencoded, the data will be converted into query string.