You have already seen the send()
method in action, when sending simple responses in some earlier examples in this chapter. The send()
method can use one of the following formats, where status
is the HTTP status code and body
is a String
or Buffer
object:
res.send(status, [body])
res.send([body])
If you specify a Buffer
object, the Content-Type
is automatically set to application/octet-stream
unless you explicitly set it to something else. For example:
res.set('Content-Type', 'text/html'),
res.send(new Buffer('<html><body>HTML String</body></html>'));
The send()
method can really handle all the responses necessary, as long as you set the appropriate headers and status for the response. Once the send()
method completes, it sets the value of the res.finished
and res.headerSent
properties. You can use these to verify that the response was sent, how much data was transferred, etc. The following is an example of the res.headerSent
property:
HTTP/1.1 200 OK
X-Powered-By: Express
Content-Type: text/html
Content-Length: 92
Date: Tue, 17 Dec 2013 18:52:23 GMT
Connection: keep-alive
Listing 18.4 illustrates some of the basics of setting the status and headers, as well as sending a response. Notice that in lines 15–18 the route for /error
sets the status to 400
before sending the response. Figure 18.3 shows the res.headerSent
data in the console output on the Express server.
01 var express = require('express'),
02 var url = require('url'),
03 var app = express();
04 app.listen(80);
05 app.get('/', function (req, res) {
06 var response = '<html><head><title>Simple Send</title></head>' +
07 '<body><h1>Hello from Express</h1></body></html>';
08 res.status(200);
09 res.set({
10 'Content-Type': 'text/html',
11 'Content-Length': response.length
12 });
13 res.send(response);
14 console.log('Response Finished? ' + res.finished);
15 console.log('
Headers Sent: '),
16 console.log(res.headerSent);
17 });
18 app.get('/error', function (req, res) {
19 res.status(400);
20 res.send("This is a bad request.");
21 });