Joi验证包中的Node js发布请求正文

时间:2018-12-19 18:27:21

标签: javascript node.js express

最近,我正在使用节点js和Joi a validation package for node。我使用正文通过postman发送帖子数据,没有参数。但是在node js应用程序中,请求正文显示为未定义。以下是这些片段:

const express = require('express');
const Joi = require('joi');
const app = express();

app.listen(3000, () => 'Server is listening on 3000');

app.post('/users', (request, response) => {
    const schema = Joi.object().keys({
        username: Joi.string()
            .alphanum()
            .min(3)
            .max(30)
            .required()
    });

    const result = Joi.validate(request.body, schema);
    response.send(result);
});

2 个答案:

答案 0 :(得分:0)

我想你忘记了正文解析器

你可以使用 body-parser 包

npm I body-parser

所以你可以像这样使用它

const bp = require('body-parser')
app.use(bp.json())

或者你可以使用 from express to

app.use(express.json())

答案 1 :(得分:-1)

use this example

const express = require('express');
const bodyParser = require('body-parser');
const Joi = require('joi');
const expressJoi = require('express-joi-validator');
var app = express();

app.use(bodyParser.json());

const schema = {
    query: {
        name: Joi.string().required()
    },
    body: {
        age: Joi.number().required(),
        company: Joi.object({
            name: Joi.string().required(),
            role: Joi.string().required().valid('HR', 'Technical') //enum style validation
        }).required()
    },
    params: {
        id: Joi.number().required()
    }
}

app.post('/testapi/:id', expressJoi(schema), function(req, res){
    res.send('validated');
});

//error handler
app.use(function (err, req, res, next) {
    if (err.isBoom) {
         return res.status(err.output.statusCode).json(err.output.payload);
    }
});

app.listen('3000',  ()=>{
    console.log(`listening to 3000`);
});