簡體   English   中英

錯誤 [ERR_HTTP_HEADERS_SENT]:發送到客戶端后無法設置標題,我無法發送表單

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

每當我想在我的視圖(ejs)中填寫表單並發送到數據庫時,我都會在終端中收到此錯誤。

    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)

這是我的代碼

我的看法


    <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>

我的路線


    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');
    });

我的模式


    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;


每當我想在我的視圖(ejs)中填寫表單並發送到數據庫時,我都會在終端中收到此錯誤。

錯誤 [ERR_HTTP_HEADERS_SENT]:發送到客戶端后無法設置標題,我無法發送表單錯誤 [ERR_HTTP_HEADERS_SENT]:發送到客戶端后無法設置標題,我無法發送表單錯誤 [ERR_HTTP_HEADERS_SENT] : 發送到客戶端后無法設置標題,我無法發送表單錯誤 [ERR_HTTP_HEADERS_SENT]:發送到客戶端后無法設置標題,我無法發送表單

當您在router.post('/mail'添加 smtp 部分出錯時,您將繼續發送郵件,因此在某些情況下,您應該向客戶端發送兩次響應,這是不可能的。您的根本問題是您正在執行兩個在單個路由器路徑和方法中進行不同的工作。我強烈建議將兩者分開。我看到您有另一個問題,它在單個頁面中有 2 個表單,具有相同的操作(它是路徑/mail POST ),分離該問題將得到解決。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM