我正在尝试使用Expess.js提交表单,但我遇到了错误

时间:2018-05-15 10:31:18

标签: node.js mongodb rest express mongoose

exports.campagne_add_post = function(req, res, next) {

    // Validate fields.
    req.assert('name', 'Please fill the name').isLength({ min: 1 }).trim().withMessage('First name must be specified.')
        .isAlphanumeric().withMessage('First name has non-alphanumeric characters.');
    req.assert('date_debut', 'Invalid date_debut').isISO8601();
    req.assert('date_fin', 'Invalid date_fin').isISO8601();
    req.assert('agence', 'Please fill agence name').isLength({ min: 1 }).trim().withMessage('Agence must be specified.')
        .isAlphanumeric().withMessage('Agence has non-alphanumeric characters.');
    req.assert('annonceur', 'Please fill the annonceur name').isLength({ min: 1 }).trim().withMessage('Annonceur name must be specified.')
        .isAlphanumeric().withMessage('Annonceur name has non-alphanumeric characters.');
    req.assert('groupe_annonceur', 'Please fill groupe annonceur').isLength({ min: 1 }).trim().withMessage('Groupe annonceur must be specified.')
        .isAlphanumeric().withMessage('Groupe annonceur has non-alphanumeric characters.');
    req.assert('produit', 'Please fill product name').isLength({ min: 1 }).trim().withMessage('Poduct name must be specified.')
        .isAlphanumeric().withMessage('Product name has non-alphanumeric characters.');

    var errors = req.validationErrors();
    console.log(errors);
    if (!errors) {

        // Sanitize fields (using wildcard).
        sanitizeBody('*').trim().escape();

        var campagne = new Campagne(
            {
                name: req.body.name,
                date_debut: req.body.date_debut,
                date_fin: req.body.date_fin,
                agence: req.body.agence,
                annonceur: req.body.annonceur,
                groupe_annonceur: req.body.groupe_annonceur,
                produit:   req.body.produit


            }
        );


        Campagne.findOne({ 'name': req.body.name })
            .exec(function (err, found_name) {
                if (err) {
                    var errors_detail = ("Error Insert : %s ", err);
                    req.flash('msg_error', errors_detail);
                    res.render('campagne/add-campagne',
                        {
                            name: req.body.name,
                            date_debut: req.body.date_debut,
                            date_fin: req.body.date_fin,
                            agence: req.body.agence,
                            annonceur: req.body.annonceur,
                            groupe_annonceur: req.body.groupe_annonceur,
                            produit:   req.body.produit,
                        });
                }
                if (found_name) {
                    req.flash('msg_error', 'Campagne with the same name already existe');
                    res.render('campagne/add-campagne',
                        {
                            name: req.body.name,
                            date_debut: req.body.date_debut,
                            date_fin: req.body.date_fin,
                            agence: req.body.agence,
                            annonceur: req.body.annonceur,
                            groupe_annonceur: req.body.groupe_annonceur,
                            produit:   req.body.produit,
                        });
                }
                else {
                    if(req.body.date_debut > req.body.date_fin){
                        req.flash('msg_error', 'date_debut must be before date_fin');
                        res.render('campagne/add-campagne',
                            {
                                name: req.body.name,
                                date_debut: req.body.date_debut,
                                date_fin: req.body.date_fin,
                                agence: req.body.agence,
                                annonceur: req.body.annonceur,
                                groupe_annonceur: req.body.groupe_annonceur,
                                produit:   req.body.produit
                            });
                    }else {

                            console.log(req.body.name +'\n');
                            console.log(req.body.date_debut +'\n');
                            console.log(req.body.date_fin +'\n');
                            console.log(req.body.agence +'\n');
                            console.log(req.body.annonceur +'\n');
                            console.log(req.body.produit);
                        campagne.save(function (err) {
                            if (err) {
                                var errors_detail = ("Error Insert : %s ", err);
                                req.flash('msg_error', errors_detail);
                                res.render('campagne/add-campage',
                                    {
                                        name: req.body.name,
                                        date_debut: req.body.date_debut,
                                        date_fin: req.body.date_fin,
                                        agence: req.body.agence,
                                        annonceur: req.body.annonceur,
                                        groupe_annonceur: req.body.groupe_annonceur,
                                        produit:   req.body.produit
                                    });
                            }

                            // Genre saved. Redirect to genre detail page.
                            req.flash('msg_info', 'Create campagne success');
                            res.redirect('/campagnes');

                        });
                    }
                }
            });
    } else {
        console.log(errors);
        errors_detail = "Sory there are error" + " <ul>" ;
        for (i in errors)
        {
            error = errors[i];
            errors_detail += ' <li>'+error.msg+'</li>';
        }
        errors_detail += "</ul>";
        req.flash('msg_error', errors_detail);
        res.render('campagne/add-campagne',
            {
                name: req.body.name,
                date_debut: req.body.date_debut,
                date_fin: req.body.date_fin,
                agence: req.body.agence,
                annonceur: req.body.annonceur,
                groupe_annonceur: req.body.groupe_annonceur,
                produit:   req.body.produit,
            });
    }
};

当我提交表单时,我收到以下消息: 错误:发送后无法设置标头。     在validateHeader(_http_outgoing.js:494:11)     在ServerResponse.setHeader(_http_outgoing.js:501:3)

我发现错误的原因之一是我的控制器中的重定向。 我在mongoose中也有一个$ __ save.error。 如果我能得到somme的帮助,那就太好了。

1 个答案:

答案 0 :(得分:1)

因为您在致电res.render时无法返回。这样,您尝试多次发送响应,因此,在发送第一个响应后设置标头。

e.g。

Campagne.findOne({ 'name': req.body.name })
   .exec(function (err, found_name) {
      if (err) {
          var errors_detail = ("Error Insert : %s ", err);
          req.flash('msg_error', errors_detail);
          // you should return here, because it can go to following condition
          return res.render('campagne/add-campagne',{ 
             // some code
          }); 
      }

      if (found_name) {
          req.flash('msg_error', 'Campagne with the same name already existe');
          return res.render('campagne/add-campagne', {
              // some code 
          });
      }

适用于所有条件。