eggjs添加获取get和post通用中间件

前言

请求有时是get,有时是post,有时本来应该是post的请求,但是为了测试方便,还是做成get和post请求都支持的请求,于是一个能同时获取get和post请求参数的中间件就很有必要了.

编写中间件的几个步骤

1.在app目录下新建middleware文件夹

  1. 在middleware里面新建params.js,内容如下
/**
 * 获取请求参数中间件
 * 可以使用ctx.params获取get或post请求参数
 */

module.exports = options => {
  return async function params(ctx, next) {
    ctx.params = {
      ...ctx.query,
      ...ctx.request.body
    }
    await next();
  };
};

本质上就是把get请求的参数和post请求的参数都放到params这个对象里,所以,不管是get还是post都能获取到请求参数

  1. 在/config/config.default.js里注入中间件
'use strict';
module.exports = appInfo => {
  const config = exports = {};
// 注入中间件
  config.middleware = [
    'params',
  ];
  return config;
};
  1. 使用
/**
 * 添加文章接口
 */

'use strict';

const Service = require('egg').Service;

class ArticleService extends Service {
  async add() {
    const { ctx } = this;
    // 获取请求参数
    const {
      userId,
      title,
      content,
    } = ctx.params;

    const result = await ctx.model.Article.create({
      userId,
      title,
      content,
    });
    return result;
  }
}
module.exports = ArticleService;

你可能感兴趣的:(eggjs添加获取get和post通用中间件)