使用传递的变量 returns 加载 express 模板时出现错误“将它们发送到客户端后无法设置 headers”

Loading express template with a passed variable returns error `Cannot set headers after they are sent to the client`

我有一个表格,我正在尝试使用 express-validator 对其进行验证。当没有验证错误时,我在控制台中没有收到任何错误,但是当出现验证错误时,我尝试将它们传递给我的 EJS 模板,但它在控制台中给我一个错误。这是我的完整代码:

var express = require('express');
var app = express();
var path = require('path');
var mongoose = require('mongoose');
var bodyParser = require('body-parser')
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}))
const { check, validationResult } = require('express-validator');

app.listen(8080);

// saytin asuma inch template piti ogtagorcvi
app.set('view engine', 'ejs');

// MongoDB
let dbUrl = 'mongodb+srv://grig:xxxXXXxxx@cluster0-osvfl.mongodb.net/test?retryWrites=true&w=majority';

mongoose.connect(dbUrl ,{useNewUrlParser : true},(err) => { 
   if (err) {
    console.log(err);
   }
});

var schema = new mongoose.Schema({ name: 'string', message: 'string' });
var User = mongoose.model('User', schema);
//

// router
app.get('/', function(req, res) {
    res.render('index');
});

app.use(express.json());
app.post('/send', [
  check('name').isLength({ min: 1 }).withMessage('Անունը չի կարող դատարկ լինել'),
  check('message').isLength({ min: 10 }).withMessage('Նամակը պետք է լինի 10 սիմվոլից ավել')
], (req, res) => {

  // Uxarkel errornery
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    res.render('index',{
      errors: errors
    });
  }

  // Stexcel userin
  User.create({
    name: req.body.name,
    message: req.body.message
  }).then(user => res.json(user));
});
//

这是我遇到的错误:

(node:6244) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:470:11)
    at ServerResponse.header (C:\xampp\htdocs\node\node_modules\express\lib\response.js:771:10)
    at ServerResponse.send (C:\xampp\htdocs\node\node_modules\express\lib\response.js:170:12)
    at ServerResponse.json (C:\xampp\htdocs\node\node_modules\express\lib\response.js:267:15)
    at User.create.then.user (C:\xampp\htdocs\node\server.js:51:23)
    at process._tickCallback (internal/process/next_tick.js:68:7)
(node:6244) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecti
ng a promise which was not handled with .catch(). (rejection id: 1)
(node:6244) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process wit
h a non-zero exit code.

我是 Node 新手,能否请您解释一下导致错误的原因。谢谢

if (!errors.isEmpty()) {
    res.render('index',{
      errors: errors
    });
  }
else {
  // Stexcel userin
  User.create({
    name: req.body.name,
    message: req.body.message
  }).then(user => res.json(user))
}

代码的 else 部分正在执行,即使有错误,它正在尝试再次发送响应。因此你得到了那个错误。或者您可以在发送错误时 return,它会解决问题。