Response methods for ExpressJS and Examples


The methods on the response object (res) in the following table can send a response to the client and terminate the request response cycle. If none of them is called from a route handler, the client request will be left hanging.

Method Description
res.download() Prompt a file to be downloaded.
res.end() End the response process.
res.json() Send a JSON response.
res.jsonp() Send a JSON response with JSONP support.
res.redirect() Redirect a request.
res.render() Render a view template.
res.send() Send a response of various types.
res.sendFile Send a file as an octet stream.
res.sendStatus() Set the response status code and send its string representation as the response body.

ExpressJS Examples


res.sendStatus

Based on status code, message will be displayed on browser.

var express = require('express');
var app = express();

app.get('/', function (req, res) {
  res.sendStatus(403);
});

app.listen(4000, function () {
  console.log('Example app listening on port 4000!');
})

res.json()

JSOn response

var express = require('express');
var app = express();

app.get('/', function (req, res) {
  res.json("{'name:'javavillage.in'}");
});

app.listen(4000, function () {
  console.log('Example app listening on port 4000!');
})

res.download()

download a file as a response

var express = require('express');
var app = express();

app.get('/', function (req, res) {
  res.download("F:/mongodb/nodejs/myapp/package.json");
});

app.listen(4000, function () {
  console.log('Example app listening on port 4000!');
})

res.render()

To simply render a static error page with the name 500 (template is the file 500.jade, the engine is Jade) and the default extension, we could use:

var express = require('express');
var app = express();
app.use(function(err, req, res, next) {
  // Do logging and user-friendly error message display
  console.error(err);
  // Assuming that template engine is plugged in
  res.render('500');
})

res.redirect()

Redirecting to error page

var express = require('express');
var app = express();
app.use(function(err, req, res, next) {    
  // Do logging and user-friendly error message display    
  res.redirect('/public/500.html')    
})

Above examples can be executed by node command as a standalone.

>node index.js