Express / Node:错误:发送后无法设置标头

时间:2016-09-13 18:58:52

标签: node.js express angular

我不确定自己是否失明,但我无法看到我试图两次发送回复的地方。 我收到错误Error: Can't set headers after they are sent.

它似乎来自transporter.sendMail()函数中发送的响应。

我的代码:

router.route('/email').post(function(req, res) {
    var dir = req.body.moduleCode
        + '/'
        + req.body.year
        + '/'
        + req.body.semester
        + '/'
        + req.body.assignCode
        + '/';

    for ( i in req.body.documentsNoExt) {
        Student.findById(req.body.documentsNoExt[i], function (err, student) {
            if (err) {
                console.log(err);
            }
            var mailOptions = {
                from : '"Feedbacker" <FeedbackerWebApp@gmail.com>',
                to: student.email,
                subject: 'Mark feedback for ' + req.body.assignCode,
                text: 'Dear ' + student.firstName + ' ' + student.lastName + ','
                + 'Please find attached your feedback for the assignment ' + req.body.assignCode + ' module ' + req.body.moduleCode + '.',
                attachments: [
                    {
                        path: './server/pdfs/' + dir + student._id + '.pdf',
                    }
                ]
            }
            transporter.sendMail(mailOptions, function(error, info) {
                if(error) {
                    console.log(error);
                }
                return res.status(200).json({ message: 'Successfully sent emails!' });
            })
        })
    }
});

这是我在angular2中的http帖子:

sendEmail(documents, assignment) {
        this.progress = 1;
        var documentsNoExt = documents.map(function (e) {
            return e.replace(/\.[^/.]+$/, "");
        });
        var emailInfo = {
            "moduleCode"    : assignment.modInsID[0].modID[0]._id,
            "year"          : assignment.modInsID[0].year,
            "semester"      : assignment.modInsID[0].semester,
            "assignCode"    : assignment.code,
            "documentsNoExt": documentsNoExt
        };
        this.authHttp.post("/api/email", JSON.stringify(emailInfo), this.options).subscribe(
            res => {
                this.sendInfoMsg("Succesfully sent E-mails.", "success");
                this.progress = 2;
            },
            err => this.sendInfoMsg(err._body, "danger")
        );
    }

任何想法,我已经两次发送回复,因为我看不出是什么导致它。

1 个答案:

答案 0 :(得分:0)

您正在循环中发送多个响应,这就是您收到此错误的原因。

  

而不是res.send(),您应该使用res.write()发送多个回复。

  

res.send()向客户端发送整个HTTP响应,其中包括headerscontent,即使是ends the response。   在那之后,你不能发送任何东西。