例如需要对前端传递的参数进行校验,我们可以使用validator.js
validator.js是一个对字符串进行数据验证和过滤的工具库,同时支持Node端和浏览器端,github地址是https://github.com/chriso/validator.js
var validator = require('validator'); validator.isEmail('foo@bar.com'); //=> true
例如对传递的id进行校验,判读是否是数字,新建一个文件,写入以下代码:
var validator = require('validator'); var isEmpty = require('../../utils/isEmpty') function validatorIsNumber(data) { let errors = {}; if (!validator.isInt(data)) { errors.message = '参数类型错误' errors.code = 400 } return { errors: errors, isValid: isEmpty(errors) }; } module.exports = validatorIsNumber;
errors错误信息,isValid是否存在错误信息false代表有错误信息
使用方法:
const Router = require('koa-router'); const router = new Router(); const validatorIsNumber = require('../../../utils/validator/book.validator') var validator = require('validator'); router.get('/v1/book/lates/:id', async (ctx, next) => { const params = ctx.params; const { errors, isValid } = validatorIsNumber('456456dsa'); console.log(isValid) if (!isValid) { const error = new global.errs(errors.code, errors.message, errors.code); throw error; } ctx.body = { code: params } }) module.exports = router
错误码列表
100 "continue"
101 "switching protocols"
102 "processing"
200 "ok"
201 "created"
202 "accepted"
203 "non-authoritative information"
204 "no content"
205 "reset content"
206 "partial content"
207 "multi-status"
208 "already reported"
226 "im used"
300 "multiple choices"
301 "moved permanently"
302 "found"
303 "see other"
304 "not modified"
305 "use proxy"
307 "temporary redirect"
308 "permanent redirect"
400 "bad request"
401 "unauthorized"
402 "payment required"
403 "forbidden"
404 "not found"
405 "method not allowed"
406 "not acceptable"
407 "proxy authentication required"
408 "request timeout"
409 "conflict"
410 "gone"
411 "length required"
412 "precondition failed"
413 "payload too large"
414 "uri too long"
415 "unsupported media type"
416 "range not satisfiable"
417 "expectation failed"
418 "I'm a teapot"
422 "unprocessable entity"
423 "locked"
424 "failed dependency"
426 "upgrade required"
428 "precondition required"
429 "too many requests"
431 "request header fields too large"
500 "internal server error"
501 "not implemented"
502 "bad gateway"
503 "service unavailable"
504 "gateway timeout"
505 "http version not supported"
506 "variant also negotiates"
507 "insufficient storage"
508 "loop detected"
510 "not extended"
511 "network authentication required"
https://blog.csdn.net/djjj123456789/article/details/81982627
发表评论
侧栏公告
寄语
譬如朝露博客是一个分享前端知识的网站,联系方式11523518。
热评文章
标签列表
热门文章
友情链接