亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

【備戰春招】第8天 eggjs

標簽:
Node.js

课程名称: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

此时就能得出校验结果

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



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





















點擊查看更多內容
TA 點贊

若覺得本文不錯,就分享一下吧!

評論

作者其他優質文章

正在加載中
Web前端工程師
手記
粉絲
27
獲贊與收藏
19

關注作者,訂閱最新文章

閱讀免費教程

  • 推薦
  • 評論
  • 收藏
  • 共同學習,寫下你的評論
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦
今天注冊有機會得

100積分直接送

付費專欄免費學

大額優惠券免費領

立即參與 放棄機會
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號

舉報

0/150
提交
取消