• Register
1 vote
1.1k views

Problem :

I am very new to the Node.js and I am having few issues.

I am using the Node.js 4.10 and Express 2.4.3.

While trying to execute my code I am receiving below error :

Error: Can't render headers after they are sent to the client.

at ServerResponse.<anonymous> (http.js:580:12)

at ServerResponse._renderHeaders (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/patch.js:70:30)

at ServerResponse.writeHead (http.js:830:30)

at /home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect-auth/lib/auth.strategies/facebook.js:30:20

at /home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect-auth/lib/index.js:120:20

at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect-auth/lib/strategyExecutor.js:50:40)

at [object Object].pass (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect-auth/lib/authExecutionScope.js:29:6)

at [object Object].halt (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect-auth/lib/authExecutionScope.js:35:9)

at [object Object].redirect (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect-auth/lib/authExecutionScope.js:20:10)

at [object Object].<anonymous> (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect-auth/lib/auth.strategies/facebook.js:80:21)

Error: Can't set headers after they are sent.

at ServerResponse.<anonymous> (http.js:540:22)

at ServerResponse.setHeader (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/patch.js:60:30)

at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:170:23)

at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:201:15)

at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:170:30)

at param (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/middleware/router.js:195:17)

at pass (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/middleware/router.js:202:16)

at Object.router [as handle] (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/middleware/router.js:209:10)

at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:204:20)

at Object.auth [as handle] (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect-auth/lib/index.js:156:9)

Error: Can't set headers after they are sent.

.

.

.

My code as below :

var realfbId= "XXX";
var realfbSecret= "XXXXXX";
var realfbCallbackAddress= "http://127.0.0.1:8888/auth/facebook_callback"
var realcookieSecret = "node";     //please  enter a random hash for security
var realexpress= require('realexpress');
var realauth = require('connect-auth')
var realapp = realexpress.createServer();
realapp.configure(function(){
    realapp.use(realexpress.bodyParser());
    realapp.use(realexpress.methodOverride());
    realapp.use(realexpress.cookieParser());
    realapp.use(realexpress.session({secret: cookieSecret}));
    realapp.use(realauth([
        realauth.Facebook({
            appId : realfbId,
           appSecret: realfbSecret,
            callback: realfbCallbackAddress,
            scope: 'offline_access,email,user_about_me,user_activities,manage_pages,publish_stream',
            failedUri: '/noauth'
        })
    ]));
   realapp.use(realapp.router);
});
.
.
.

 

7.5k points

Please log in or register to answer this question.

2 Answers

0 votes

Solution :

If you are using the callback functions then use the return after the err block. This is one of the most frequent scenarios in which this error can happen.

realuserModel.createUser(data, function(realerr, realdata) {

    if(realerr) {

      res.status = 422

      res.json(realerr)

      return // without this return the error can happen.

    }

    return res.json(realdata)

  })

I had Tested it on Node version v10.16.0 and express 4.16.4

 

38.6k points
0 votes

Solution:

The res object in Express is a subclass of Node.js's http.ServerResponse (read the http.js source). You are allowed to call res.setHeader(name, value) as often as you want until you call res.writeHead(statusCode). After writeHead, the headers are baked in and you can only call res.write(data), and finally res.end(data).

The error "Error: Can't set headers after they are sent." means that you're already in the Body or Finished state, but some function tried to set a header or statusCode. When you see this error, try to look for anything that tries to send a header after some of the body has already been written. For example, look for callbacks that are accidentally called twice, or any error that happens after the body is sent.

In your case, you called res.redirect(), which caused the response to become Finished. Then your code threw an error (res.req is null). and since the error happened within your actual function(req, res, next) (not within a callback), Connect was able to catch it and then tried to send a 500 error page. But since the headers were already sent, Node.js's setHeader threw the error that you saw.

Good Middleware

Code:

// middleware that does not modify the response body
var doesNotModifyBody = function(request, response, next) {
  request.params = {
    a: "b"
  };
  // calls next because it hasn't modified the header
  next();
};

// middleware that modify the response body
var doesModifyBody = function(request, response, next) {
  response.setHeader("Content-Type", "text/html");
  response.write("<p>Hello World</p>");
  response.end();
  // doesn't call next()
};

app.use(doesNotModifyBody);
app.use(doesModifyBody);

 

Problematic Middleware

var problemMiddleware = function(request, response, next) {
  response.setHeader("Content-Type", "text/html");
  response.write("<p>Hello World</p>");
  next();
};

The problematic middleware sets the response header without calling response.end() and calls next(), which confuses connect's server.

31.7k points