Based on the Promise WeChat applet http request, it is lightweight, compact, API-friendly, and rich in functions.
yarn add wechat-request
npm install wechat-request --save
import wxRequest from 'wechat-request';
First let’s make a simple get
request
// 向具有给定ID的用户发出请求
wxRequest . get ( '/user?id=12345' )
. then ( function ( response ) {
console . log ( response ) ;
} )
. catch ( function ( error ) {
console . log ( error ) ;
} ) ;
// 可选地,上面的请求也可以按照
wxRequest . get ( '/user' , {
params : {
id : 'number'
}
} ) . then ( function ( response ) {
console . log ( response ) ;
} ) . catch ( function ( error ) {
console . log ( error ) ;
} ) ;
// 想要使用 async/await? 将`async`关键字添加到外部函数/method
async function getUser ( ) {
try {
const response = await wxRequest . get ( '/user?ID=12345' ) ;
console . log ( response ) ;
} catch ( error ) {
console . error ( error ) ;
}
}
Use async/waait in various ways to start a convenient and enjoyable journey of coding
Then come another post
request
wxRequest . post ( '/user' , {
firstname : 'firstname' ,
lastname : 'lastname'
} ) . then ( function ( response ) {
console . log ( response ) ;
} ) . catch ( function ( error ) {
console . log ( error ) ;
} ) ;
Example of executing multiple concurrent requests
function getUserAccount ( ) {
return wxRequest . get ( '/user/12345' ) ;
}
function getUserPermissions ( ) {
return wxRequest . get ( '/user/12345/permissions' ) ;
}
wxRequest . all ( [ getUserAccount ( ) , getUserPermissions ( ) ] )
. then ( response => {
// dosoming ...
} ) ;
Of course, in addition to the common get
and post
requests, other requests are also packaged uniformly.
wxRequest.request(config)
wxRequest.get(url[, config])
wxRequest.delete(url[, config])
wxRequest.head(url[, config])
wxRequest.options(url[, config])
wxRequest.post(url[, data[, config]])
wxRequest.put(url[, data[, config]])
wxRequest.patch(url[, data[, config]])
note: When using alias method
url
,method
anddata
attributes do not need to be specified in the config.
Usage scenarios User requests require tokens or address prefixes, which can be configured once, saving time and worry.
wxRequest . defaults . baseURL = 'https://api.example.com' ;
wxRequest . defaults . headers [ 'Authorization' ] = AUTH_TOKEN ;
wxRequest . defaults . headers . post [ 'Content-Type' ] = 'application/x-www-form-urlencoded' ;
MIT