Detailed explanation of how easy and simple sends a response in KOA

Recently made a lot of back-end projects, wrote a lot of interfaces, but found that as the interface slowly increased, more and more more and more The following code.

ctx.body = {data: {name: ‘test’}, status: {code: 0, message: success}}
Write it into this flex, at least the format uniform returned by all interfaces. If it is not specified in this regard, then the interface of the background returns will not be uniform, which will bring a lot of problems to the front end.
And each interface must write such a large number of code. It feels a special trouble.

So Koa2-Response is born. In fact, before writing this article, I have used it in my project for a while, which is convenient for our operation.


】 Usage
Const Koa = Require (‘Koa’); Const Router = Require (‘Koa-router’) (); const app = new koa ( ); const response = Require (‘KOA2-Response’); const code = {unknown_error: [1, ‘sorry, you see way.’]} Router .gET (‘/’, (ctx, next) => {response.success (CTX, {Name: ‘Test’}) .get (‘/ error_test’, (ctx, next) => {response.ERROR CTX, CODE.UNKNOWN_ERROR);}) app.use (router.Routes ()); app.use (router.allowedmethods ()); app.listen (3000);

It is very simple to reunite back data, which makes me save a lot of time in the project. This middleware is still in continuous updates, and now there is a method that is response.success and response. error. I intend to continue to update a method called response.throw, which allows the background to customize the returned HTTP status code and error message. For example, the user has no permissions, and the status code of HTTP should be 401, and should not be our custom code.

Written in the back
   If there is a better solution, I hope I will enlighten me. 
GitHub Transfer Gate KOA2-Response

The above is all the content of this article, I hope to help everyone, I hope everyone will support Tumi Clouds.

© Copyright Notice
Just support it if you like
comment Grab the couch

Please log in to comment