1

i keep getting this error in my terminal anytime i want to fill the form in my view(ejs) and send to the database.

    MongoDB Connected



    Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
        at ServerResponse.setHeader (_http_outgoing.js:485:11)
        at ServerResponse.header (/home/codabae/Documents/mailmonster/api/v1/node_modules/express/lib/response.js:767:10)
        at ServerResponse.send (/home/codabae/Documents/mailmonster/api/v1/node_modules/express/lib/response.js:170:12)
        at done (/home/codabae/Documents/mailmonster/api/v1/node_modules/express/lib/response.js:1004:10)
        at tryHandleCache (/home/codabae/Documents/mailmonster/api/v1/node_modules/ejs/lib/ejs.js:257:5)
        at View.exports.renderFile [as engine] (/home/codabae/Documents/mailmonster/api/v1/node_modules/ejs/lib/ejs.js:482:10)
        at View.render (/home/codabae/Documents/mailmonster/api/v1/node_modules/express/lib/view.js:135:8)
        at tryRender (/home/codabae/Documents/mailmonster/api/v1/node_modules/express/lib/application.js:640:10)
        at Function.render (/home/codabae/Documents/mailmonster/api/v1/node_modules/express/lib/application.js:592:3)
        at ServerResponse.render (/home/codabae/Documents/mailmonster/api/v1/node_modules/express/lib/response.js:1008:7)
        at /home/codabae/Documents/mailmonster/api/v1/node_modules/express-ejs-layouts/lib/express-layouts.js:113:20
        at tryHandleCache (/home/codabae/Documents/mailmonster/api/v1/node_modules/ejs/lib/ejs.js:257:5)
        at View.exports.renderFile [as engine] (/home/codabae/Documents/mailmonster/api/v1/node_modules/ejs/lib/ejs.js:482:10)
        at View.render (/home/codabae/Documents/mailmonster/api/v1/node_modules/express/lib/view.js:135:8)
        at tryRender (/home/codabae/Documents/mailmonster/api/v1/node_modules/express/lib/application.js:640:10)
        at Function.render (/home/codabae/Documents/mailmonster/api/v1/node_modules/express/lib/application.js:592:3)

here is my code

my view


    <h1 class="mt-4">Dashboard</h1>
    <div class="row mt-5">
        <div class="col-md-6 m-auto">
          <div class="card card-body">
            <h1 class="text-center mb-3">
              <i class="fas fa-user-plus"></i> Add Smtp
            </h1>
            <% include ./partials/messages %>
            <form action="/users/mail" method="POST">
              <div class="form-group">
                <label for="smtpUsername">smtpUsername</label>
                <input
                  type="name"
                  id="smtpUsername"
                  name="smtpUsername"
                  class="form-control"
                  placeholder="Enter smtpUsername"
                  value="<%= typeof smtpUsername != 'undefined' ? smtpUsername : '' %>"
                />
              </div>
              <div class="form-group">
                <label for="smtpPassword">smtpPassword</label>
                <input
                  type="name"
                  id="smtpPassword"
                  name="smtpPassword"  
                  class="form-control"
                  placeholder="Enter smtpPassword"
                  value="<%= typeof smtpPassword != 'undefined' ? smtpPassword : '' %>"
                />
              </div>
              <div class="form-group">
                <label for="smtpUrl">smtpUrl</label>
                <input
                  type="name"
                  id="smtpUrl"
                  name="smtpUrl"
                  class="form-control"
                  placeholder="Enter smtpUrl"
                  value="<%= typeof smtpUrl != 'undefined' ? smtpUrl : '' %>"
                />
              </div>
              <button type="submit" class="btn btn-primary btn-block">
                Add Smtp
              </button>
            </form>
          </div>
        </div>
      </div>



    <div class="row mt-5">
        <div class="col-md-6 m-auto">
          <div class="card card-body">
            <h1 class="text-center mb-3">
              <i class="fas fa-user-plus"></i> send mail
            </h1>
            <% include ./partials/messages %>
            <form action="/users/mail" method="POST">
              <div class="form-group">
                <label for="to">to</label>
                <input
                  type="name"
                  id="to"
                  name="to"
                  class="form-control"
                  placeholder="Enter to"
                  value="<%= typeof to != 'undefined' ? to : '' %>"
                />
              </div>
              <div class="form-group">
                <label for="bcc">bcc</label>
                <input
                  type="name"
                  id="bcc"
                  name="bcc"
                  class="form-control"
                  placeholder="Enter bcc"
                  value="<%= typeof bcc != 'undefined' ? bcc : '' %>"
                />
              </div>
              <div class="form-group">
                <label for="cc">cc</label>
                <input
                  type="name"
                  id="cc"
                  name="name"
                  class="form-control"
                  placeholder="Enter cc"
                  value="<%= typeof cc != 'undefined' ? cc : '' %>"
                />
              </div>
              <div class="form-group">
                <label for="subject">subject</label>
                <input
                  type="name"
                  id="subject"
                  name="subject"
                  class="form-control"
                  placeholder="Enter subject"
                  value="<%= typeof subject != 'undefined' ? subject : '' %>"
                />
              </div>
              <div class="form-group">
                <label for="message">message</label>
                <input
                  type="name"
                  id="message"
                  name="message"
                  class="form-control"
                  placeholder="Enter message"
                  value="<%= typeof message != 'undefined' ? message : '' %>"
                />
              </div>
              <button type="submit" class="btn btn-primary btn-block">
                Register
              </button>
            </form>
          </div>
        </div>
      </div>



    <a href="/users/logout" class="btn btn-secondary">Logout</a>

my routes


    router.get('/mail', forwardAuthenticated, (req, res) =>
        res.render('mail', {
            user: req.user,
            mail: req.mail

        })
    );
    router.post('/mail', (req, res) => {
        const { to, cc, bcc, subject, message, attachment,smtpUrl, smtpUsername, smtpPassword  } = req.body;

        console.log(smtpUrl)
        console.log(smtpPassword)
        console.log(smtpUsername)



        let errors = [];

        if (!smtpUrl || !smtpUsername || !smtpPassword) {
            errors.push({ msg: 'Add an account' });
            res.render('mail', {
            smtpUrl,
            smtpPassword,
            smtpUsername
            });

        }else{
          console.log(smtpUrl)
          console.log(smtpPassword)
          console.log(smtpUsername)
          const newSmtp = new Smtp({
            smtpUrl,
            smtpPassword,
            smtpUsername
        });

        newSmtp
        .save()
        .then(mail => {
            req.flash(
                'success_msg',
                'Account Added'
            );

        })
        .catch(err => console.log(err));
        }
        if (!to || !subject || !message) {
            errors.push({ msg: 'Please enter all fields' });
        }


        if (errors.length > 0) {
            res.render('mail', {
                errors,
                to,
                cc,
                bcc,
                subject,
                message,
                attachment,
            });
        } else {
            const newMail = new Mail({
                to,
                cc,
                bcc,
                subject,
                message,
                attachment,
            });


            let transporter = nodemailer.createTransport({
                service: smtpUrl,
                auth: {
                    user: smtpUsername,
                    pass: smtpPassword
                }
            });

            let mailOptions = {
                from: smtpUsername,
                to: to,
                subject: subject,
                text: `${message}`
            };

            transporter.sendMail(mailOptions, function (error, info) {
                if (error) {
                    console.log(error);
                } else {

                    newMail
                        .save()
                        .then(mail => {
                            req.flash(
                                'success_msg',
                                'mail sent'
                            );

                        })
                        .catch(err => console.log(err));
                    console.log('Email sent: ' + info.response);
                }
            });





        }


    })

    // Login
    router.post('/login', (req, res, next) => {
      passport.authenticate('local', {
        successRedirect: '/users/mail',
        failureRedirect: '/users/login',
        failureFlash: true
      })(req, res, next);
    });

    // Logout
    router.get('/logout', (req, res) => {
      req.logout();
      req.flash('success_msg', 'You are logged out');
      res.redirect('/users/login');
    });

my schema


    const mongoose = require('mongoose');

    const MailSchema = new mongoose.Schema({
        to: {
            type: String,

        },
        cc: {
            type: String,

        },
        bcc: {
            type: String,
        },
        subject: {
            type: String,

        },
        message: {  
            type: String,

        },
        attachment: {
            type: String,
        },
        date: {
            type: Date,
            default: Date.now
        },

    });

    const SmtpSchema = new mongoose.Schema({
        smtpUrl: {
            type: String,
            required: true

        },
        smtpUsername: {
            type: String,
            required: true

        },
        smtpPassword: {
            type: String,
            required: true

        },
        date: {
            type: Date,
            default: Date.now
        },

    });





    const Mail = mongoose.model('Mail', MailSchema);
    const Smtp = mongoose.model('Smtp', SmtpSchema);


    module.exports = Mail;
    module.exports = Smtp;


i keep getting this error in my terminal anytime i want to fill the form in my view(ejs) and send to the database.

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client, i can't send a form Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client, i can't send a form Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client, i can't send a form Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client, i can't send a form

CodaBae
  • 275
  • 2
  • 6
  • 16
  • 1
    Please comment the res.render() call in your POST /mail request. This could be the source of your error. – Wasbeer Jan 26 '20 at 15:52
  • 1
    Adding to @Wasbeer's answer, you might as well check this post out. https://stackoverflow.com/questions/7042340/error-cant-set-headers-after-they-are-sent-to-the-client – akhildhiman Jan 26 '20 at 16:12

1 Answers1

1

When you have an error on add smtp part in router.post('/mail', you continue for sending mail, so in some cases you should twice send response to client and that is impossible. Your fundamental problem is that you are doing two different work in a single router path and method. I strongly recommend separating the two. I saw you have another question that had 2 form in a single page with the same action (It was POST in path /mail), with separating that problem will be solved.

Milad Aghamohammadi
  • 1,866
  • 1
  • 16
  • 29