当前位置:网站首页>Advanced cross platform application development (II): uni app practice

Advanced cross platform application development (II): uni app practice

2022-07-01 05:39:00 No Silver Bullet


One 、 Preface

In the early post 《 Advanced cross platform application development ( One ) approach uni-app》 in , Explained the use of uni-app Basic knowledge of cross end development of framework , This blog post mainly explains uni-app Actual combat process and knowledge points involved .

Two 、 Project practice

2.1 Style framework

uni-ui The extension component complies with easycom Component specifications , It can be directly applied to .

If the component does not meet easycom standard , You need to manually... In the code import And register components , And then you can use it .

standard js and browser js The difference between

  • uni-app Of js Code ,h5 The client runs in the browser . Not h5 End ( Contains applets and App),Android The platform runs on v8 engine in ,iOS The platform runs on iOS Self contained jscore In the engine , Are not running in the browser or webview in .

  • Not H5 End , Though not in favor of window、document、navigator And so on js API, But it also supports standards ECMAScript.

  • Don't put the browser's js Extension object is equivalent to standard js.

  • uni-app Non - H5 End , Support standards as well js, Support if、for Equal grammar , Support string 、 Numbers 、 Time 、 Boolean value 、 Array 、 Custom object and other variable types and various processing methods . It just doesn't support window、document、navigator Browser specific objects such as .

2.2 Routing jump

  • uni.navigateTo(OBJECT)
    Keep the current page , Jump to a page in the app , Use uni.navigateBack You can go back to the original page .

Be careful ️:

  • The page Jump path has hierarchical restrictions , You can't jump to new pages without restrictions ;
  • Jump to tabBar The page can only use switchTab Jump ;
  • route API The target page must be in pages.json Registered in vue page . If you want to open web url, stay App The platform can use plus.runtime.openURL or web-view Components ;H5 Platform use window.open; The applet platform uses web-view Components (url Need to be in the applet's online white list ). stay hello uni-app There are components in ulink.vue Multiple terminals have been encapsulated , May refer to .
  • APP-NVUE The platform does not support this.getOpenerEventChannel() How to get eventChannel, Please change it this.$scope.eventChannel To get , Please refer to the above example for details .
  • uni.navigateBack(OBJECT)
    Close current page , Go back to the previous page or multi-level page . It can be done by getCurrentPages() Get the current page stack , Decide how many layers you need to go back .

  • uni.redirectTo(OBJECT)
    Close current page , Jump to a page in the app .

  • uni.reLaunch(OBJECT)
    Close all pages , Open to a page in the app .

Be careful ️:

  • If called uni.preloadPage(OBJECT) Will not close , Just trigger the lifecycle onHide.

  • H5 End calls uni.reLaunch After that, the page stack will be destroyed , But you can't empty the history before the browser , here navigateBack Can't return , If there is a history, click the browser's back button or call history.back() You can still navigate to other browser history .

  • uni.switchTab(OBJECT)
    Jump to tabBar page , And shut down all the others tabBar page .

2.3 Request backstage

  1. In the catalog service So let's make a new one request.js file , encapsulate .
mport {
    
	baseURL
} from './config.js'
import {
    
	getToken,
	goToLogin
} from '@/common/util.js'

const setToken = (res) => {
    
	if (res.hasOwnProperty("access_token")) {
    
		getApp().globalData.token = getToken(res.token_type, res.access_token)
		console.log('token info is: ', getApp().globalData.token)
	}
	if (res.hasOwnProperty('msg')) {
    
		if (res.msg === ' User credentials have expired ') {
    
			goToLogin()
		}
	}
};

const handleErr = (err) => {
    
	uni.hideLoading()
	uni.showModal({
    
		title: ' Tips ',
		content: err.errMsg,
		showCancel: false,
		success: function(res) {
    
			if (res.confirm) {
    
				// console.log(' The user clicks ok ');
			} else if (res.cancel) {
    
				// console.log(' The user clicks cancel ');
			}
		}
	});
};

const request = (url, params, method, tips) => {
    
	uni.showLoading({
    
		title: tips || " Loading ..."
	})
	const curUrl = (url.indexOf('http') !== -1 || url.indexOf('https') !== -1) ? url : baseURL + url
	console.log('The request url info is: ', curUrl)
	console.log('The request params info is: ', params)
	return new Promise((resolve, reject) => {
    
		uni.request({
    
			url: curUrl,
			method: method || "POST",
			header: {
    
				'Content-Type': 'application/json',
				'Authorization': getApp().globalData.token || 'Basic YXBwOmFwcA=='
			},
			data: params || {
    },
			success(res) {
    
				setToken(res.data)
				resolve(res.data)
				console.log('The request success return info is: ', res.data)
			},
			fail(err) {
    
				reject(err)
				console.log('The request fail return info is: ', err)
			},
			complete() {
    
				uni.hideLoading()
			}
		})
	}).catch(err => {
    
		handleErr(err)
	})
};

export {
    
	requestForm,
	requestJSON
}

  1. stay common Create a folder together utils.js Files are used to get token.
//  obtain token
export function getToken(token_type, access_token) {
    
	let token = token_type.charAt(0).toUpperCase() + token_type.slice(1) + ' ' + access_token;
	return token;
}

// Model Prompt whether to return to the login page 
export function goToLogin() {
    
	uni.showModal({
    
		title: ' reminder ',
		content: " You haven't signed in yet , Please log in ",
		success: function(res) {
    
			if (res.confirm) {
    
				// console.log(' The user clicks ok ');
				uni.navigateTo({
    
					url: '/pages/ucenter/userinfo/userinfo'
				})
			} else if (res.cancel) {
    
				// console.log(' The user clicks cancel ');
			}
		}
	})
}

  1. Create a new one api Catalog , Then corresponding pages Create a directory and file with the corresponding name on the page ,list.js A file is a request interface .
//  Introduce tool classes 
import request from '@/service/request.js' 
 
export function get(data){
     // 
    return request({
    
        url: '/forshop/getprefer',
        method: 'GET',
        contentType:'application/x-www-form-urlencoded',
        data: data
     })
}

Be careful ️:uni.request If no incoming success / fail / complete Parameters , Will return encapsulated by default Promise object .

  1. Then on the page list.vue Call interface .
<script>
	import {
     get } from "@/api/list/list"
	export default {
    
		methods: {
    
			get().then(res => {
    
				console.log(res)
			}).catch (err => {
    
				console.log(err)
			})
		}
	}
</script>

The above is promise Form of interface request .await The interface request mode of form is :

import {
     get } from "@/api/list/list"
// Await
async function request () {
    
   var [err, res] = await get({
    
       url: 'https://www.example.com/request'
   });
   console.log(res.data);
}

2.4 uni-app https Request mode

Conventional HTTP There are the following security issues :

  1. Communicate in clear text , Content may be bugged ;

  2. Do not verify the identity of the communicating party , The identity of the communication party may be disguised ;

  3. Can't prove the integrity of the message , The message may be tampered with .

To solve the problem of secure communication ,HTTPS emerge as the times require . Actually ,HTTPS It's not a new agreement , But standing HTTP On my shoulder , Give Way HTTP The first and SSLSecure Sockets Layer) signal communication , Again by SSL and TCP signal communication , in other words HTTPS Communication using tunnels . By using SSL,HTTPS Possess encryption ( Anti wiretapping )、 authentication ( Anti camouflage ) and Integrity protection ( tamper-proof ).
 Insert picture description here

2.4.1 encryption

(1) Symmetric key encryption (Symmetric-Key Encryption), Encryption and decryption use the same key .
 Insert picture description here
(2) Asymmetric key encryption , Also known as public key encryption (Public-Key Encryption), Encryption and decryption use different keys .

The public key is available to all , After the communication sender obtains the public key of the receiver , You can use the public key to encrypt , After receiving the communication content, the receiver uses the private key to decrypt . Asymmetric keys are used for encryption , It can also be used to sign . Because private key can't be obtained by others , Therefore, the communication sender uses its private key To sign , The receiver decrypts the signature with the sender's public key , We can judge whether the signature is correct .
 Insert picture description here
HTTPS Using mixed encryption mechanism , Use Asymmetric key Encryption is used for transmission Symmetric key To ensure the security of the transmission process , Then use Symmetric key Encrypt the communication to ensure the efficiency of the communication process .
 Insert picture description here

2.4.2 authentication

Authenticate the communicating party by using a certificate .

Digital certificate authority (CA,Certificate Authority) It is a third-party organization that both client and server can trust . The operator of the server asked CA Apply for a public key ,CA After identifying the applicant , Will do digital signature to the applied public key , Then distribute the signed public key , And put the public key into the public key certificate and bind it together . Conduct HTTPS When communication , The server will send the certificate to the client . After the client obtains the public key , First use digital signature for verification , If the verification passes , You can start communicating .

2.4.3 Integrity protection

SSL Provide message digest function for integrity protection . HTTP Also provided MD5 Message summary function , But it's not safe . For example, after the message content has been tampered with , And recalculate MD5 Value , The communication receiver is not aware of the tampering .

HTTPS The message digest function of is secure , Because it combines encryption and authentication These two operations . Just imagine , Encrypted message , After being tampered with , It's also hard to recalculate message digest , Because it's not easy to get plaintext .

2.4.4 HTTPS The shortcomings of

  • Because of the need for encryption and decryption , So it's going to be slower ;

  • A high fee for Certificate Authorization is required .

uni-app application https Request mode , Need to cooperate with SSL certificate :

If it is HTTPS Access Certificate , It should be the server configuration , When the front end initiates a request , The address is written as https The prefix is enough , for example :https://www.example.com/login

2.5 Application planning 、 Configuration and adjustment

It's not that there's SSL The certificate will be all right , Also consider the use in the application , Need to plan 、 Server configuration 、 Application adjustment and other links .

because SSL Than http It takes more cpu resources ( Mainly in the phase of establishing handshake connection , Then encrypt the content ), So for general websites , Only some places need to use https, Most open content is unnecessary , Depending on your business requirements . For example, for many websites with low security requirements , Not at all https It is also acceptable .

Some pages support both http and https , Or just support https、 mandatory https

At the same time, support means that users can access it with any protocol , Then the user's request is mainly guided by the link of the page itself , Because ordinary users will not modify the address bar on their own .

Generally, our website can support http and https, All accessible . But it's easy to have the problem of mixed content or mixed script .

It can also be planned to support some pages https, Generally, public pages don't need https, Just change the links in some places to https That's all right. . Specifically expect to https In the page visited , The absolute of reference URL Can be used explicitly https link .

Forced or not https ? For websites with high security or some pages in the website , Can be forced to use https visit , Even if users manually put... In the address bar https Change it to http, Will also be automatically redirected back to https On . For example, you can configure web The server rewrite The rules put these http url Automatically redirect to the corresponding https url On ( This makes maintenance easier ), Without changing the application .

2.6 Application market on the shelf

application HBuilder When the cloud packs , Prompt the following verification information :
 Insert picture description here
among , The main tip is “ The current app lacks relevant configuration ”, The following measures can be taken to solve :

open HBuilder Project manifest.json file , Switch to “ Source view ” term

uni-app project

stay “app-plus” -> “privacy” Add under node prompt node .

5+ App project

stay “plus” -> “privacy” Add under node prompt node .

  • prompt String type , Required , Privacy policy prompt box configuration policy , Value for template、custom、none, The default value is none.

  • template Use the native prompt box template , Customizable title 、 The content has the text on the button .

  • custom Customize privacy policy prompt box ,uni-app It is recommended to use nvue Customize the page ,5+ APP Use html Customize the page .

  • none Do not pop up the privacy policy prompt box

  • template json Format , Optional , What is displayed on the template prompt box

 "privacy": {
    
	"prompt": "template",
	"template": {
    
		"title": " Service agreement and privacy policy ",
		"message": "   Please read carefully 、 Full understanding “ The service agreement ” and “ Privacy policy ” Articles , Including but not limited to : In order to better serve you , We need to collect your device identification 、 Operation logs and other information are used for analysis 、 Optimize application performance .<br/>   You can read <a href="">《 The service agreement 》</a> and <a href="">《 Privacy policy 》</a> Learn more . If you agree to , Please click the button below to start accepting our service .",
		"buttonAccept": " I got it! ",
		"buttonRefuse": " Disagree for the time being "
	}
}

3、 ... and 、 Expanding reading

原网站

版权声明
本文为[No Silver Bullet]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202160213201573.html