• Register
1 vote
875 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);
});
.
.
.

 

6 5 3
7,540 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

 

9 7 4
38,600 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.

10 6 4
31,120 points

Related questions

0 votes
1 answer 24 views
24 views
Problem: HELP me to deal with this : Error: route.get() requires a callback function but got a [object undefined].
asked Mar 6 Wafa Abu Yousef 6.1k points
0 votes
1 answer 3.4K views
3.4K views
Problem : I am just starting coding using the nodejs with express. So I simply did this in my file test.js which is into my folder routes : const myexpress = require('express'); const myrouter = new myexpress.Router(); myrouter.get('/test', (req, res) => { res.send(` ... browser, it tells me it Cannot get/test I don't understand why this is happening to me. Please let me know how can I fix this?
asked Jan 23, 2020 jwilliam 3.9k points
0 votes
1 answer 3 views
3 views
Problem I got an error in the console when I'm executing the node code: SyntaxError: expected expression, got '<' What's I&rsquo;m missing here ?
asked Mar 22 ummesalma 21.9k points
0 votes
1 answer 22 views
22 views
Problem : Facing following express issue throw new typeerror('router.use() requires a middleware function but got a ' + gettype(fn)) any help?!
asked Mar 6 Wafa Abu Yousef 6.1k points
0 votes
1 answer 147 views
0 votes
2 answers 4.4K views
4.4K views
Problem : Facing following express issue throw new typeerror('router.use() requires a middleware function but got a ' + gettype(fn))
asked Nov 18, 2019 peterlaw 6.9k points
0 votes
1 answer 14 views
14 views
Problem: Did anybody face the same issue: It looks like you are trying to access mongodb over http on the native driver port.
asked Mar 14 Wafa Abu Yousef 6.1k points
0 votes
1 answer 2.1K views
2.1K views
Problem : When I try to open the terminal and enter the following command: sudo mongod The output is received as below: [initandlisten] waiting for connections on port 27017 When I try to open another terminal and enter following command: sudo mongo I will open the mongo ... never posts the data. So I think my problem lies within mongo but I am unable to figure it out. POST /info 200 120002ms
asked Dec 12, 2019 alecxe 7.5k points
1 vote
1 answer 29 views
29 views
Problem : How to fix this error: TypeError: Cannot read property 'path' of undefined
asked Mar 21 Shovo210 13.2k points
0 votes
1 answer 5 views
5 views
Problem: I am using node with express + mongoose and trying to use passport.js with restful api. I keep getting this exception after authentication success (I see the callback url on the browser): Passport.initialize() middleware not in use
asked Apr 2 ummesalma 21.9k points