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 : { } } )
变更日志