Keith Grout
Keith Grout

Reputation: 919

Can't set headers after they're sent

I have an issue I've seen on here before, but I dont' know why it's happening in my "app". I am getting the "can't set headers after they're sent" error whenever I just go to the route, /. I'm sure I'm missing something basic. I've looked at the documentation and I've looked at other answers here, but I still can't seem to see why this would happen. Can someone please walk through why this error is occuring?

When I change writeHead to setHeader, everything works accordingly. Where else would I have sent the headers other than /?

// Basic Setup
var express = require('express')
, app = express()
, bodyParser = require('body-parser')
, port = process.env.PORT || 3000;

// Middleware
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());

// Setup Routes
var router = express.Router();

router.get('/about', function(req, res){
  res.json({name: "tester"});
});

router.get('/', function(req, res){
  res.writeHead('200', {"Content-Type": 'text/html'});
  res.send("<html><head></head><body>Welcome to something. Sent from server.</body>        </html>");
});

app.use('/', router);

app.listen(port);
console.log("listening on port " + port);`

Upvotes: 0

Views: 746

Answers (2)

sharath yadhav
sharath yadhav

Reputation: 546

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).

Try this:

Any exceptions within middleware function(req, res, next) (Connect/Express only)
res.send(body|status[, headers|status[, status]]) (Express only)

Upvotes: 1

Waqas Ahmed
Waqas Ahmed

Reputation: 493

SetHeader:

Sets a single header value for implicit headers. If this header already exists in the to-be-sent headers, it's value will be replaced. Use an array of strings here if you need to send multiple headers with the same name.

As Given Here:

http://nodejs.org/docs/v0.4.0/api/http.html#response.setHeader

WriteHead :

Sends a response header to the request. The status code is a 3-digit HTTP status code, like 404. The last argument, headers, are the response headers. Optionally one can give a human-readable reasonPhrase as the second argument.

This method must only be called once on a message and it must be called before response.end() is called.

If you call response.write() or response.end() before calling this, the implicit/mutable headers will be calculated and call this function for you.

As Given Here:

http://nodejs.org/docs/v0.4.0/api/http.html#response.writeHead

Upvotes: 1

Related Questions