简体   繁体   中英

Express & Casper: Can't set headers after they are sent

I'm getting a Can't set headers after they are sent error when trying to run a SpookyJS (a driver for CasperJS) script after posted to a URL. I've found several other posts about people running this issue with Express and it has to do with the headers being sent multiple times and stuff. I'm just not sure how this relates with what I'm doing here. I have to have res.send to send the status of the request, right? Because if I don't have it, the form doesn't post.

Any ideas what I'm doing wrong here?

app.post('/submit', function (req, res) {
    // Send callback
    res.send(req.status);

    var spooky = require('spooky').create({   
        verbose: true,
        logLevel: 'debug',
        userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_8) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22',
        pageSettings: {
            loadImages:  false,
            loadPlugins: false
        }
    });

    spooky.start('http://google.com', function () {
        this.echo(this.getTitle());
    });

    // Run Spooky
    spooky.run();
});

The error "Error: Can't set headers after they are sent." means that you're already in the Body or Finished state and there is something which is trying to write to header.

You have this res.send(req.status); right at the beginning of callback and after this you are trying to do some more operations which are trying to set a header or status code but body has already been written. So you are seeing this error.

You should send response in the end, more importantly try to understand the asynchronous behaviour of node.js.

Move res.send(req.status); to last line of callback, your code will work then.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM