1

我无法让这段非常基本的代码在新版本中工作。这是我的代码

const express = require("express");
const bodyParser = require("body-parser");
const validator = require("express-validator");
const { check, validationResult } = require("express-validator/check");

    const app = express(); 
    app.use(bodyParser.json());
    app.use(validator());

    app.post('/',
             [ check("email").isEmail() ],
             (req, resp) => { 
                const errors = validationResult(req);
                resp.send(errors.mapped()); });
    
app.listen(3000, () => { console.log('listening on port 3000'); });

我发送了一个包含正文的发布请求:

{ "email": "ha@gmail.com" }

即使我提供的电子邮件完全正确,响应总是错误

{ "email": { "location": "body", "param": "email", "msg": "Invalid value" } }

我错过了什么吗?

4

1 回答 1

3

那是因为req.body.emailis always undefined,您必须通过添加以下行来告诉body-parser中间件将传入的请求主体解析为对象:

app.use(bodyParser.urlencoded({ extended: true }));

另一件事,始终用于errors.isEmpty()检查验证是否包含错误:

app.post('/send', [ check("email").isEmail() ], (req, resp) => { 

    console.log(req.body);

    const errors = validationResult(req);

    if (!errors.isEmpty()) {
        return resp.send(errors.mapped()); 
    }

    resp.send('no errors');

});
于 2018-02-10T01:32:13.947 回答