继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

【备战春招】第8天 eggjs

有梦
关注TA
已关注
手记 82
粉丝 25
获赞 19

课程名称:Node.js工程师养成计划


课程章节: 第九章


课程讲师:北瑶



课程内容

        

    在 model 里面建立一个 user.js 用于链接mongoose

module.exports = app => {
  const mongoose = app.mongoose
  const Schema = mongoose.Schema
  const UserSchema = new Schema({
    username: {
      type: String,
      required: true
    },
    email: {
      type: String,
      required: true
    },
    password: {
      type: String,
      required: true,
      select:false
    },
    phone: {
      type: String,
      required: true
    },
    image: {
      type: String,
      default: null
    },
    cover:{
      type: String,
      default: null
    },
    channeldes:{
      type: String,
      default: null
    },
    subscribeCount:{
      type:Number,
      default:0
    }
  })
  return mongoose.model('User', UserSchema)
}

连接mongodb 并给 password 设置了 查询时不显示 

select:false


新建 controller 文件夹

'use strict';

const { Controller } = require('egg');

class HomeController extends Controller {
  async index() {
    var userinfo = await this.app.model.User.find()
    this.ctx.body = userinfo
  }
}

module.exports = HomeController;
this.app.model.User 会自动找到 app文件下得 model 下的 user.js

关于数据校验

npm i egg-validate

config 文件下 plugin。js

module.exports.validate = {
  enable: true,
  package: 'egg-validate',
};


设置为开启状态


然后创建 middleware  - error_handler.js

module.exports = () => {
  return async function errorHandler(ctx, next) {
    try {
      await next();
    } catch (err) {
      // 所有的异常都在 app 上触发一个 error 事件,框架会记录一条错误日志
      ctx.app.emit('error', err, ctx);

      const status = err.status || 500;
      // 生产环境时 500 错误的详细错误内容不返回给客户端,因为可能包含敏感信息
      const error =
        status === 500 && ctx.app.config.env === 'prod'
          ? 'Internal Server Error'
          : err.message;

      // 从 error 对象上读出各个属性,设置到响应中
      ctx.body = { error };
      if (status === 422) {
        ctx.body.detail = err.errors;
      }
      ctx.status = status;
    }
  };
};

设置全局得错误处理

需要再 config.default.js 引入

  config.middleware = ['errorHandler'];

const Controller = require('egg').Controller
class UserController extends Controller {
  async create() {
    const { ctx } = this

    ctx.validate({
      username: { type: 'string' },
      email: { type: 'string' },
      password: { type: 'string' },
    })

    ctx.body = 'user'
  }
}

module.exports = UserController

此时就能得出校验结果

http://img4.sycdn.imooc.com/63ec25a40001767603980153.jpg



http://img1.sycdn.imooc.com/63ec25ba0001e39409470533.jpg





















打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP