Skip to content

res.end should finish response#102

Closed
mctep wants to merge 2 commits into
expressjs:masterfrom
mctep:master
Closed

res.end should finish response#102
mctep wants to merge 2 commits into
expressjs:masterfrom
mctep:master

Conversation

@mctep

@mctep mctep commented Nov 26, 2014

Copy link
Copy Markdown

Hello. Thanks for your job.

I have some code in express:

var express = require('express');
var session = require('express-session');
var request = require('supertest');

var app = express();

app.use(session({
    resave: true,
    saveUninitialized: true,
    secret: 'test'
}));

app.get('/',
    function(req, res, next) {
        var someBigIsolateLogic = true;
        if (someBigIsolateLogic) {
            res.send('I have some result');
        }

        // I don't know about big logic
        // and what it have to send or not send.
        // 
        // I have to send default content.
        if (!res.finished) {
            res.send('Default result');
        }
    }
);

request(app).get('/').expect(200).end(function() {});

In some places I rely on the res.finished to find out whether the response has finished. And if it has not, I send the default result.

But the code above throws the Error('Can't set headers after they are sent.') because the original req.end is called asynchronously, and it doesn't set the req.finished as true at the right time. And without using session this code works as expected.

My PR resolves this problem, and I think it looks like hack. But I worked out nothing better.

@dougwilson

Copy link
Copy Markdown
Contributor

This may be reasonable, but your change has some edge cases. I can fix them and get something in this week.

@dougwilson dougwilson self-assigned this Nov 26, 2014
@dougwilson

Copy link
Copy Markdown
Contributor

In the meantime, you should change your code, as it's currently broken. Your code should be checking http://nodejs.org/api/http.html#http_response_headerssent (res.headersSent) before setting headers, because res.finished is false even when you're not allowed to set headers any more, regardless of this module. This module just brought that bug in your code to light.

@mctep

mctep commented Nov 26, 2014

Copy link
Copy Markdown
Author

Oh, yes. You are absolutely right. Thank you so much.
I think my PR is unuseful. So I close it.

@mctep mctep closed this Nov 26, 2014
@expressjs expressjs locked and limited conversation to collaborators Nov 29, 2014
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants