摘要:入門筆記請(qǐng)按照官方文檔初始化一個(gè)工程項(xiàng)目,按照如下步驟學(xué)習(xí)即可,如有不懂的請(qǐng)參考官方文檔。需要禁止此特性。定義為字符串且必須,最小長(zhǎng)度為個(gè)字符。下面將定義統(tǒng)一錯(cuò)誤處理的中間件進(jìn)行錯(cuò)誤處理。在目錄中創(chuàng)建目錄,對(duì)的內(nèi)置對(duì)象進(jìn)行擴(kuò)展即可。
入門筆記
請(qǐng)按照官方文檔初始化一個(gè)simple工程項(xiàng)目,按照如下步驟學(xué)習(xí)即可,如有不懂的請(qǐng)參考官方文檔。
禁止csrf驗(yàn)證根據(jù)如下步驟進(jìn)行控制的創(chuàng)建,在執(zhí)行Post操作的時(shí)候會(huì)出現(xiàn)invalid csrf token錯(cuò)誤。需要禁止此特性。
創(chuàng)建路由/** * @param {Egg.Application} app - egg application */ module.exports = app => { const { router, controller, } = app; router.get("/", controller.home.index); // 新建資源路由 router.resources("SystemUser", "/system/user", controller.system.user); };
控制器controller.system.user,對(duì)應(yīng)的是controller目錄下的system目錄里面的user.js文件
創(chuàng)建對(duì)應(yīng)的控制器const Controller = require("egg").Controller; class SystemUserController extends Controller { async index() { const { ctx, } = this; ctx.body = "hello ! this is SystemUserController"; } } module.exports = SystemUserController;
訪問(wèn)地址:localhost:7001/system/user
創(chuàng)建可以提交數(shù)據(jù)的控制器方法const Controller = require("egg").Controller; class SystemUserController extends Controller { async index() { const { ctx, } = this; ctx.body = "hello ! this is SystemUserController"; } async create() { const ctx = this.ctx; const user = ctx.request.body; ctx.body = user; } } module.exports = SystemUserController;
POST方法訪問(wèn)網(wǎng)址:localhost:7001/system/user 會(huì)提示invalid csrf token錯(cuò)誤。
關(guān)閉csrf驗(yàn)證// configconfig.default.js // 關(guān)閉csrf驗(yàn)證 config.security = { csrf: { enable: false, }, };開(kāi)啟驗(yàn)證
在上面的例子中,我們通過(guò)表單提交了任何數(shù)據(jù),都會(huì)回顯到界面上,如果是數(shù)據(jù)需要存儲(chǔ)或者做其他業(yè)務(wù)處理,則需要對(duì)用戶輸入的數(shù)據(jù)進(jìn)行驗(yàn)證。
egg提供了egg-validate插件進(jìn)行表單驗(yàn)證
cnpm install egg-validate --save配置啟用插件
/** @type Egg.EggPlugin */ module.exports = { // had enabled by egg // static: { // enable: true, // } validate: { enable: true, package: "egg-validate", }, };使用驗(yàn)證組件
首先創(chuàng)建一個(gè)規(guī)則,這里我們定義username是字符串而且是必須的,最大長(zhǎng)度為8個(gè)字符。
定義password為字符串且必須,最小長(zhǎng)度為6個(gè)字符。
ctx.validate(createRule, ctx.request.body);
通過(guò)上述語(yǔ)句進(jìn)行參數(shù)檢查
更多規(guī)則請(qǐng)參考:https://github.com/node-modul...
const Controller = require("egg").Controller; // 定義本接口的請(qǐng)求參數(shù)的驗(yàn)證規(guī)則 const createRule = { username: { type: "string", required: true, max: 8, }, password: { type: "string", required: true, min: 6, }, }; class SystemUserController extends Controller { async index() { const { ctx, } = this; ctx.body = "hello ! this is SystemUserController"; } async create() { const ctx = this.ctx; // 驗(yàn)證輸入?yún)?shù)是否符合預(yù)期格式 ctx.validate(createRule, ctx.request.body); const user = ctx.request.body; ctx.body = user; } } module.exports = SystemUserController;測(cè)試
使用POSTMAN提交任意字段,則會(huì)提示Validation Failed (code: invalid_param)
如何查看具體錯(cuò)誤信息呢。下面將定義統(tǒng)一錯(cuò)誤處理的中間件進(jìn)行錯(cuò)誤處理。
在項(xiàng)目的app目錄中創(chuàng)建middleware目錄,此目錄中可以創(chuàng)建中間件。
創(chuàng)建錯(cuò)誤處理中間件"use strict"; module.exports = () => { return async function errorHandler(ctx, next) { try { await next(); } catch (err) { // 控制臺(tái)輸出 console.error("MiddleWare errorHandler", err); // 所有的異常都在 app 上觸發(fā)一個(gè) error 事件,框架會(huì)記錄一條錯(cuò)誤日志 ctx.app.emit("error", err, ctx); // status 如果沒(méi)有,則統(tǒng)一為500 const status = err.status || 500; // 如果是500錯(cuò)誤,且是生產(chǎn)環(huán)境,則統(tǒng)一顯示“Internal Server Error” const error = status === 500 && ctx.app.config.env === "prod" ? "Internal Server Error" : err; // 改變上下文狀態(tài)代碼 ctx.status = status; // 從 error 對(duì)象上讀出各個(gè)屬性,設(shè)置到響應(yīng)中 ctx.body = { error, }; } }; };啟用中間件
文件configconfig.default.js中
// add your middleware config here config.middleware = [];
將其修改為包含你創(chuàng)建的中間件
// add your middleware config here // errorHandler 統(tǒng)一錯(cuò)誤處理 config.middleware = [ "errorHandler" ]; // errorHandler 只在/api上生效 config.errorHandler = { match: "/api", };
如上所示,可以設(shè)置錯(cuò)誤處理中間件在什么URL上面起作用。這里我們使用/api
測(cè)試路由先使用原來(lái)的路由訪問(wèn):localhost:7001/system/user
錯(cuò)誤提示依舊
變更路由:打開(kāi)文件:approuter.js
// router.resources("SystemUser", "/system/user", controller.system.user); router.resources("SystemUser", "/api/v1/system/user", controller.system.user);
再次訪問(wèn):localhost:7001/api/v1/system/user
提示信息會(huì)變成:
{"error":{"message":"Validation Failed","code":"invalid_param","errors":[{"message":"required","field":"username","code":"missing_field"},{"message":"required","field":"password","code":"missing_field"}]}}格式化接口返回的數(shù)據(jù)結(jié)構(gòu)
在上面顯示錯(cuò)誤信息中,可以看到規(guī)范的Json數(shù)據(jù),如果開(kāi)發(fā)接口,我們就需要定義統(tǒng)一的數(shù)據(jù)結(jié)構(gòu),以便客戶端進(jìn)行解析。
在API開(kāi)發(fā)中,可以定義接口的標(biāo)準(zhǔn)返回格式。通過(guò)框架擴(kuò)展方式定義返回?cái)?shù)據(jù)格式是一個(gè)非常方便的方法。
在app目錄中創(chuàng)建extend目錄,對(duì)egg的內(nèi)置對(duì)象Helper進(jìn)行擴(kuò)展即可。
文件:app/extend/helper.js
"use strict"; module.exports = { /** * 調(diào)用正常情況的返回?cái)?shù)據(jù)封裝 * @param {Object} ctx - context * @param {*} msg - message * @param {*} data - 數(shù)據(jù) */ success(ctx, msg, data) { ctx.body = { code: 0, msg, data, }; ctx.status = 200; }, /** * 處理失敗,處理傳入的失敗原因 * @param {*} ctx - context * @param {Object} res - 返回的狀態(tài)數(shù)據(jù) */ fail(ctx, res) { ctx.body = { code: res.code, msg: res.msg, data: res.data, }; ctx.status = 200; }, };改造統(tǒng)一錯(cuò)誤處理
// 從 error 對(duì)象上讀出各個(gè)屬性,設(shè)置到響應(yīng)中 // ctx.body = { // error, // }; // 格式化返回錯(cuò)誤信息 ctx.helper.fail(ctx, { code: status, msg: error.message, data: error.errors, });測(cè)試
再次訪問(wèn):localhost:7001/api/v1/system/user
提示信息會(huì)變成:
{ "code": 422, "msg": "Validation Failed", "data": [ { "message": "required", "field": "username", "code": "missing_field" }, { "message": "required", "field": "password", "code": "missing_field" } ] }將控制器user中的返回改為標(biāo)準(zhǔn)格式
async create() { const ctx = this.ctx; // 驗(yàn)證輸入?yún)?shù)是否符合預(yù)期格式 ctx.validate(createRule, ctx.request.body); const user = ctx.request.body; // ctx.body = user; this.ctx.helper.success(this.ctx, "ok", user); }
提交滿足要求的數(shù)據(jù),測(cè)試正確的返回?cái)?shù)據(jù)
username testuser
password 1234567890
提交后將返回標(biāo)準(zhǔn)的數(shù)據(jù)格式
{ "code": 0, "msg": "ok", "data": { "username": "testuser", "password": "1234567890" } }
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請(qǐng)注明本文地址:http://www.ezyhdfw.cn/yun/102143.html
摘要:基于對(duì)象字面量,但是獨(dú)立于任何編程語(yǔ)言,真正重要的是表示法本身,所以在學(xué)習(xí)之前不必先學(xué)習(xí)。鍵必須是字符串,值可以是合法的數(shù)據(jù)類型字符串?dāng)?shù)字對(duì)象數(shù)組布爾值或。布爾類型中的布爾值僅可使用小寫(xiě)形式或,其他任何寫(xiě)法都會(huì)報(bào)錯(cuò)。 什么是JSON JSON全稱是Javascript Object Notation(對(duì)象表示法),是一種在不同平臺(tái)間傳遞數(shù)據(jù)的文本格式(數(shù)據(jù)交換格式)。常見(jiàn)的數(shù)據(jù)交換格式...
摘要:基于對(duì)象字面量,但是獨(dú)立于任何編程語(yǔ)言,真正重要的是表示法本身,所以在學(xué)習(xí)之前不必先學(xué)習(xí)。鍵必須是字符串,值可以是合法的數(shù)據(jù)類型字符串?dāng)?shù)字對(duì)象數(shù)組布爾值或。布爾類型中的布爾值僅可使用小寫(xiě)形式或,其他任何寫(xiě)法都會(huì)報(bào)錯(cuò)。 什么是JSON JSON全稱是Javascript Object Notation(對(duì)象表示法),是一種在不同平臺(tái)間傳遞數(shù)據(jù)的文本格式(數(shù)據(jù)交換格式)。常見(jiàn)的數(shù)據(jù)交換格式...
摘要:第二章學(xué)習(xí)流程圖函數(shù)轉(zhuǎn)換為模塊函數(shù)轉(zhuǎn)換為模塊后,就可以靈活的使用模塊,方便代碼分類,避免代碼堆積在一個(gè)文件上。使用命令打包代碼,生成發(fā)布包打包后會(huì)生成目錄和文件發(fā)布后會(huì)多了目錄和文件,這個(gè)是發(fā)布的生成的包和相關(guān)配置文件。 head first python(第二章)--學(xué)習(xí)流程圖showImg(http://source1.godblessyuan.com/blog_head_firs...
摘要:前言本系列文章是學(xué)習(xí)過(guò)程的一個(gè)記錄初步目標(biāo)是寫(xiě)一個(gè)個(gè)人博客會(huì)盡可能多使用中提供的各種功能本文全部使用請(qǐng)確保版本足夠支持文中有不正確地方請(qǐng)指正地址文檔初始化項(xiàng)目使用腳手架初始化項(xiàng)目選擇初始化項(xiàng)目的類型項(xiàng)目目錄結(jié)構(gòu)自定義啟動(dòng)時(shí) 前言 本系列文章是Egg學(xué)習(xí)過(guò)程的一個(gè)記錄,初步目標(biāo)是寫(xiě)一個(gè)個(gè)人博客,會(huì)盡可能多使用Egg中提供的各種功能.本文全部使用 async 請(qǐng)確保Node版本足夠支持.文...
閱讀 815·2021-11-22 13:52
閱讀 1618·2021-09-27 13:36
閱讀 2942·2021-09-24 09:47
閱讀 2326·2021-09-22 15:48
閱讀 3678·2021-09-22 15:39
閱讀 1548·2019-08-30 12:43
閱讀 2995·2019-08-29 18:39
閱讀 3339·2019-08-29 12:51