我正在尝试使用Joi和Node创建API身份验证,但是是否需要通过电子邮件发送邮递员的请求,还是不要求仅显示电子邮件?。
这是路由文件夹中的users.js
const express = require('express');
const router = require('express-promise-router')();
const {validateBody,schemas} = require('../helpers/routeHelpers');
const UserController = require('../controllers/users');
router.route('/signup')
.post(validateBody(schemas.authSchema), UserController.signUp);;
router.route('/login')
.post(UserController.login);
router.route('/secret')
.get(UserController.secret);
module.exports = router;
这是控制器功能中的users.js
module.exports={
signUp : async(req,res,next)=>{
console.log('usercontroller.signup() called!');
},
login: async(req,res,next)=>{
console.log('usercontroller.login() called!');
},
secret : async(req,res,next)=>{
console.log('usercontroller.secret() called!');
}
}
最后是routehelper.js
const Joi = require('joi');
module.exports = {
validateBody: (schema) => {
return (req, res, next) => {
const result = Joi.validate(req.body, schema);
if (result.error) {
return res.status(400).json(result.error);
}
if (!req.value) { req.value = {}; }
req.value['body'] = result.value;
next();
}
},
schemas: {
authSchema: Joi.object().keys({
email: Joi.string().email().required(),
password: Joi.string().required()
})
}
}
起初,我从邮递员发送了一个发帖请求而没有电子邮件,然后我收到了这个错误
{
"isJoi": true,
"name": "ValidationError",
"details": [
{
"message": "\"email\" is required",
"path": [
"email"
],
"type": "any.required",
"context": {
"key": "email",
"label": "email"
}
}
],
"_object": {}
}
然后我使用电子邮件ID和passowrd发送,但仍然出现相同的错误
我的原始请求看起来像这样..
{“电子邮件”:“ app@gmail.com”,“密码”:“密码”}