Node.js抛出新的错误('不能在发送后设置标题。');

时间:2015-08-28 09:29:33

标签: node.js express

这个错误:

{}
_http_outgoing.js:335
    throw new Error('Can\'t set headers after they are sent.'); Error: Can't set headers after they are sent.
    at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:335:11)
    at ServerResponse.setWriteHeadHeaders (D:\xampp\htdocs\wisaa\node_express\node_modules\morgan\node_modules\on-headers\index.js:80:19)
    at ServerResponse.writeHead (D:\xampp\htdocs\wisaa\node_express\node_modules\morgan\node_modules\on-headers\index.js:39:36)
    at ServerResponse.writeHeader (_http_server.js:233:18)
    at Object.queue.drain (D:\xampp\htdocs\wisaa\node_express\routes\index.js:52:13)
    at D:\xampp\htdocs\wisaa\node_express\node_modules\async\lib\async.js:871:23
    at D:\xampp\htdocs\wisaa\node_express\node_modules\async\lib\async.js:44:16
    at D:\xampp\htdocs\wisaa\node_express\routes\index.js:43:21
    at Socket.<anonymous> (D:\xampp\htdocs\wisaa\node_express\node_modules\email-verify\index.js:145:13)
    at Socket.emit (events.js:129:20)

npm ERR! Windows_NT 6.2.9200 npm ERR! argv "C:\\Program Files (x86)\\nodejs\\\\node.exe" "C:\\Program Files (x86)\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "start" npm ERR! node v0.12.5 npm ERR! npm  v2.11.2 npm ERR! code ELIFECYCLE npm ERR! node_express@0.0.0 start: `node ./bin/www` npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the node_express@0.0.0 start script 'node ./bin/www'. npm ERR! This is most likely a problem with the node_express package, npm ERR! not with npm itself. npm ERR! Tell the author that this fails on your system: npm ERR!     node ./bin/www npm ERR! You can get their info via: npm ERR!     npm owner ls node_express npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request: npm ERR!     D:\xampp\htdocs\wisaa\node_express\npm-debug.log`

这是我的代码:

var express = require('express');
var router = express.Router();
var _ = require('underscore');
var fs = require('fs'),
    async = require('async'),
    verifier = require('email-verify');
/* GET home page. */

router.post('/', function(req, res, next) {

    var emails = req.body.emails;

    emails = emails.split(',');

    var queue = async.queue(function(task, callback) {
        task(callback);
    }, 100);
    _.each(emails, function(e, i) {
        queue.push(function(cb) {
            var done = false;
            verifier.verify(e, function(err, info) {
                if (err) {
                    //console.log(err);
                    // fauile
                    emails.splice(emails.indexOf(e), 1);
                    var score = "Your email is nor valid neither exist";
                } else {
                    if (info.success) {
                        // success
                        res.json({
                            'message': emails
                        });
                    } else {
                        emails.splice(emails.indexOf(e), 1);
                    }
                }
                if (!done) {
                    done = true;
                    cb(null, true);
                    console.log('something bad happened!');
                }
            });
        });

    });
    queue.drain = function() {
        console.log(arguments);
        res.writeHeader(200, {
            'content-Type': 'text/plain'
        });
        res.send(JSON.stringify(emails));
        res.end();
    }
});
module.exports = router;

3 个答案:

答案 0 :(得分:1)

您似乎每次请求都会调用res.json()一次或多次。这是不允许的,因为它发送响应(并且标题因此错误)。每个请求应该只有一个响应。

执行_.each时,您正在制作循环。在这种情况下,您要将一堆函数添加到队列中。处理该队列中的每个功能后,您将调用res.json()res.json()会发送一个您只能执行一次而非多次的响应。

如果你需要,你可以对这个队列中所需的电子邮件进行任何处理,但实际上不能用res.json发送它,直到调用回调为止,所以{{1} }。

答案 1 :(得分:0)

正如@Matt Harrison已经指出的那样,我只想添加一点描述。

看起来像,

res.json({
            'message':emails
            });
首先调用

,它负责将json响应发送到客户端,从而完成请求 - 响应周期。

因此,在此之后,对res对象的任何尝试都是无关紧要的,因为已经发送了响应。

由于您遇到异常

new Error('Can\'t set headers after they are sent.');

因此,最有可能的是,调用queue.drain(),即设置标头。此时您将收到错误。

答案 2 :(得分:0)

尝试:

verifier.verify(e, function(err, info) {
    if (err) {
       //Return the error itself
       return res.send(err);
       //The rest of your code here
       ...
}else{...}

你需要添加&#39; return&#39;这样你就不会两次回复。简而言之,您的代码需要有returnelse,因此如果出现错误,您就不会执行这两个代码路径。在我看来,这就是错误的来源。

希望这有帮助。!