English|中文
Egg-response version | egg 1.x |
---|---|
1.x | 😁 |
0.x | ❌ |
$ npm i egg-response --save
or
$ yarn add egg-response
// config/plugin.js
exports.response = {
enable: true,
package: 'egg-response',
};
// {app_root}/app/controller/post.js
ctx.successful(data[,options]);
// or
ctx.failed([options]);
Create a successful response
Parameter
- data - the data returned by the response
- options (optional) -
Object
with the following optional attributes:- isData -
boolean
, whether to return data, the default value istrue
,If set to false, the returned json fielddata
will be replaced bymessage
- code -
int
, response status code, default value is200
- extra -
Object
, additional information
- isData -
Example
ctx.successful([1,2,3],{
extra: {
xxx: 'Additional message'
}
});
- Returns the result, will be in json format, as follows:
{
"success": true,
"code": 200,
"data": [1,2,3],
"xxx": "Additional message"
}
Create a failed response
Parameter
- options (optional) -
Object
with the following optional attributes:- message - error message, default value is 'Request error'
- code - response status code, default value is
500
- extra - append message
Example
ctx.failed({ message: 'There is no such category' });
- Returns the result,will be in json format, as follows:
{
"code": 500,
"success": false,
"message": "There is no such category"
}
with
Go to config/config.default.js for detailed configuration item descriptions.
Please go to [egg issues] (https://github.com/iamljw/egg-response/issues) for asynchronous communication.