• Register
1 vote
671 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 2.4K views
2.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 1.6K views
1.6K 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
0 votes
1 answer 100 views
0 votes
2 answers 3.1K views
3.1K 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
1 vote
1 answer 511 views
511 views
Problem: I am very new to node so I think I am making something extremely wrong here as I am unable to find any info at all by doing research online. I already have the django site and I required the JS charting library so I chose the chart.js. I have ... build a chart. Failed to create chart: can't acquire context from the given item . Please help me in fixing above NodeJs elated error.
asked Jun 4, 2020 Martin K 6.6k points
0 votes
2 answers 508 views
508 views
Problem : I want to to run my NodeJS version with the nvm but getting following error: $ nvm use v4.2.4 nvm is not compatible with the npm config "prefix" option: currently set to "/Users/z/.npm-global"Run `npm config delete prefix` or `nvm use --delete- ... it. I have set the prefix on purpose to avoid the sudo npm How can I use nvm without losing the prefix for my globally installed packages?
asked Nov 29, 2019 alecxe 7.5k points
0 votes
2 answers 413 views
413 views
Problem : I am new to Programming. I have created a Maven Project, the JavaScript project is cloned as the git sub-module inside Maven Project. My directory structure is as below mavenapp/src/main/javascript/[npm project files] and inside the package.json my test is looking as below : " ... install But it is not working for me.. npm version : 5.5.1 node version : 9.3.0 How can I fix above error?
asked Mar 3, 2020 mphil 2.3k points
0 votes
1 answer 1.6K views
1.6K views
Problem : I am beginner in the node.js .Currently I am trying to install node.js using the below command npm install nodemon --save. But when I try to run a server with below command nodemon server.js. then in my terminal I face below error: &ldquo;Nodemon is not recognized as internal or external command, operable program or batch file&rdquo;
asked Feb 13, 2020 mphil 2.3k points
0 votes
1 answer 176 views
176 views
Problem : I have recently updated the node to 7.2.1 and noticed that there is the warning coming as below : (node:4346) DeprecationWarning: Calling an asynchronous function without callback is deprecated. Why is this 4346 ? I only have 2000 lines of code in the js file, so it must not be the line-number. Where should I look for that code?
asked Dec 10, 2019 alecxe 7.5k points
0 votes
1 answer 1.4K views
1.4K views
Problem : I am new to NodeJS and trying to connect to mySQL through the NodeJS file, however I am facing the below error : { Error: ER_ACCESS_DENIED_ERROR: Access denied for user 'root'@'localhost' (using password: YES) at Handshake.Sequence._packetToError (/home/alecxe/Node ... bar" AS second_field', function(err, results, fields) { console.log(err); console.log(results); myconnection.end(); } );
asked Dec 6, 2019 alecxe 7.5k points