[Solved-2 Solutions] Error: Can't set headers after they are sent to the client



Error Description:

  • When we try to access , we’ll be redirected to .
  • we then receive the following error:
 headers

Learn sql - sql tutorial - headers - sql examples - sql programs

The following is the code:

var fbId= "XXX";
var fbSecret= "XXXXXX";
var fbCallbackAddress= "http://127.0.0.1:8888/auth/facebook_callback"

var cookieSecret = "node";     // enter a random hash for security

var express= require('express');
var auth = require('connect-auth')
var app = express.createServer();
app.configure(function(){
    app.use(express.bodyParser());
    app.use(express.methodOverride());
    app.use(express.cookieParser());
    app.use(express.session({secret: cookieSecret}));
    app.use(auth([
        auth.Facebook({
            appId : fbId,
            appSecret: fbSecret,
            callback: fbCallbackAddress,
            scope: 'offline_access,email,user_about_me,user_activities,manage_pages,publish_stream',
            failedUri: '/noauth'
        })
    ]));
    app.use(app.router);
});

app.get('/auth/facebook', function(req, res) {
  req.authenticate("facebook", function(error, authenticated) {
    if (authenticated) {
      res.redirect("/great");
      console.log("ok cool.");
      console.log(res['req']['session']);
    }
  });
});

app.get('/noauth', function(req, res) {
  console.log('Authentication Failed');
  res.send('Authentication Failed');
});

app.get('/great', function( req, res) {
  res.send('Supercoolstuff');
});

app.listen(8888);
click below button to copy the code. By - sql tutorial - team

Solution 1:

  • The res object in Express is a subclass of Node.js's http.ServerResponse (read the http.js source) We are allowed to call res.setHeader(name, value) as often as we want until we call res.writeHead(statusCode). After writeHead, the headers are baked in and we can only call res.write(data) , and finally res.end(data).
  • The error "Error: Can't set headers after they are sent." means that we’re already in the Body or Finished state, but some function tried to set a header or statusCode. When we 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.

Solution 2:

We might be calling res.redirect without a return statement, so the next function was also being called immediately afterwards:

auth.annonymousOnly = function(req, res, next) {
    if (req.user) res.redirect('/');
    next();
};
click below button to copy the code. By - sql tutorial - team

Which should have been:

auth.annonymousOnly = function(req, res, next) {
    if (req.user) return res.redirect('/');
    next();
};
click below button to copy the code. By - sql tutorial - team

Related Searches to Error: Can't set headers after they are sent to the client