A network request component library based on wx.request extension provided for WeChat applet.
npm install weapp.request -S
const request = require ( 'weapp.request' )
Send a GET request
request ( 'https://api.github.com' ) . then ( onFulfilled ) . catch ( onRejected )
Because all request
calls will return a Promise
, you can use then
to further process the request results, and use catch
to capture internally thrown errors.
Send a GET request and write to cache
request ( 'https://api.github.com' , { } , {
cache : true
} )
Send a POST request
request . post ( 'https://api.github.com' , {
user : 'afishhhhh'
} )
Except for GET requests, all other methods must be called in the form of request.method
.
According to the WeChat official documentation, the above POST method and the default Content-Type
is application/json
, and the data will be JSON serialized.
If you need to send data to the server in the form of query string, you can use the following calling method. You do not need to write Content-Type
as application/x-www-form-urlencoded
explicitly:
request . post ( 'https://api.github.com' , {
form : {
user : 'afishhhhh'
}
} )
Global configuration
Configuration options | type | illustrate | Required | default value |
---|---|---|---|---|
baseUrl | String/Undefined | Basic request path | no | |
cacheMaxAge | Number/Undefined | Cache validity period, time unit is seconds | no | 1800 |
validStatusCode | Function/Undefined | status code legal range, this function accepts one parameter and returns a Boolean | no | code => code >= 200 && code < 300 |
request . config ( {
baseUrl : 'https://api.github.com'
} )
Request/response interceptor
// 添加请求拦截器
request.interceptors.req.use(function (request) {
request.header['X-Tag'] = 'weapp.request'
// return request 可以显式地返回一个 request,如果没有 return,则默认返回当前 request
})
The same goes for response interceptors.
// 移除请求拦截器
request.interceptors.req.remove()
request(url, params, options)
Make a GET request.
params
: request parameters, type is Object
, optional.
options
: configuration item, type is Object
, optional, can have the following attribute values:
property | type | Required | default value | illustrate |
---|---|---|---|---|
cache | Boolean/Undefined | no | undefined | undefined means to obtain the latest data from the server and not write it into the cache; true means to obtain the data from the cache first. If the data does not exist in the cache or the cache has expired, the data will be obtained from the server and written to the cache; false means to obtain the data from the server first. Get data and write data to cache |
header | Same as WeChat official document | |||
dataType | Same as WeChat official document | |||
responseType | Same as WeChat official document |
request.method(url, params, options)
method
can be get
, post
etc.
request.config(options)
options
: Configuration items, type is Object
.
This code is distributed under the terms and conditions of the MIT license.