weapp next
1.0.0
Weapp(微信小程式)官方API封裝,旨在暴露時尚、友善、流暢的程式API。
Promised 非同步 API
wx.request
API 的捷徑
增強官方 API
RESTful http 用戶端
# via Github
npm i xixilive/weapp-next --save-dev
# via npm
npm i weapp-next --save-dev
const weapp = require ( 'weapp-next' ) ( wx )
const client = weapp . Http ( 'https://api.server.com/' )
//async/await
async function postLogin ( ) {
const { code } = await weapp . login ( )
const { errMsg , ... userInfo } = await weapp . getUserInfo ( { withCredentials : true } )
return await client . post ( '/login' , { data : { ... userInfo , code } } )
}
//promise
function postLogin ( ) {
const getUserInfo = code => opts => {
return weapp . getUserInfo ( opts ) . then ( ( { errMsg , ... userInfo } ) => ( { userInfo , code } )
}
const postRequest = data => client . post ( '/login' , { data } )
return weapp . login ( ) . then ( getUserInfo ) . then ( postRequest )
}
weapp-next
使用 UMD 模組系統,您可以以 Commonjs 或 AMD 格式載入它。
import weapp from 'weapp-next'
// get wrapped wx Object
const { request , Http } = weapp ( wx )
// use request API
request ( { url : 'https://test.com' , method : 'GET' } ) . then ( response => console . log )
// use shortcuts of request API, such as get, post, put, etc.
request . get ( 'https://test.com' ) . then ( response => console . log )
// use Http client
const http = Http ( 'https://server.com/api' )
http . get ( '/path' ) . then ( response => console . log )
// or
const weapp = require ( 'weapp-next' ) ( wx )
封裝了幾乎所有官方API,請參閱封裝方法
根據微信小程式聲明的動詞(RFC 2616)建立http請求捷徑。特別是, PATCH
動詞對於嚴格的 RESTful 主義者可能有用,因此它也被定義了。
weapp.request
它解析採用 [200, 300) 範圍內的 statusCode 的反應,並拒絕超出該範圍的反應。
已解決的回應和拒絕的原因/錯誤是來自本機wx.request
的回應物件。
import weapp from 'weapp-next'
const { request } = weapp ( wx )
request ( { url , method : 'GET' } )
. then ( response => {
// response is the response object from wx.request
} )
. catch ( error => {
// error is the response object from wx.request
} )
request . get ( url : String [ , init : Function ] )
request . post ( url : String , body : String / Object , [ , init : Function ] )
request . put ( url : String , body : String / Object , [ , init : Function ] )
request . patch ( url : String , body : String / Object , [ , init : Function ] )
request . delete ( url : String [ , init : Function ] )
request . head ( url : String [ , init : Function ] )
request . options ( url : String [ , init : Function ] )
request . trace ( url : String [ , init : Function ] )
request . connect ( url : String [ , init : Function ] )
可選的init
參數是一個零參數函數,用於插入請求參數,並且它期望按照約定傳回一個物件值。您可以透過傳回的物件覆寫除url
和method
之外的任何請求參數。
// logic of init function
const config = { ... }
return { ... config , ... init ( ) , url , method }
weapp.requireAuth
(已棄用)貶值
這是一個用於 weapp 登入場景的 Express 中間件,旨在輕鬆整合 weapp 登入和 getUserInfo 邏輯。快遞 Weapp 身份驗證
import weapp from 'weapp-next'
const http = weapp ( wx ) . Http ( 'https://api.server.com/' )
http . get ( '/status' , { version : '1' } ) // /status?version=1
http . post ( '/status' , { data : { } } )
變更日誌