Home  >  Article  >  Web Front-end  >  A simple way to send responses in Koa

A simple way to send responses in Koa

不言
不言Original
2018-07-21 11:26:441904browse

This article shares with you a simple way to send responses in Koa. The content is very good. Friends in need can refer to it. I hope it can help everyone.

Background

Recently I have done a lot of node backend projects and written a lot of interfaces, but I found that as the number of interfaces slowly increased, more and more things needed to be written. Much like the code below.

ctx.body = {
    data: {
        name: 'test'
    },
    status: {
        code: 0,
        message: success
    }
}

It’s okay to write it like this, at least the format returned by all interfaces is unified. If there is no standardization in this regard, then the backend interface returns are not uniform, which will bring a lot of problems to the front end.

And each interface requires writing such a lot of code. It feels like a particularly troublesome thing.

So koa2-response was born. In fact, before writing this article, I have been using it in my project for some time, which facilitates our operations.

Installation

npm install koa2-response

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 seem to have encountered some unknown errors.']
}

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 unify the return data of the backend. This method allows I save a lot of time on my projects. This middleware is still being continuously updated, and the existing methods are response.success and response.error. I plan 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, if the user does not have permission, the http status code should be 401, not our custom code.

Related recommendations:

How to use the FileReader object to obtain the code of the image

The above is the detailed content of A simple way to send responses in Koa. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn