Class: Response

Response

Response


new Response(props)

Do not initialize this class on your own. An instance of this class is provided to your handler as a parameter.

Parameters:
Name Type Description
props Object

Members


<readonly> app :App

App object, used to access application-wide settings.

Type:
See:

<readonly> body :string

HTTP response body

Type:
  • string
Example
res.send({ foo: 'bar' });
res.body // => '{"foo":"bar"}'

<readonly> finished :boolean

Whether the HTTP response has already been sent

Type:
  • boolean
Example
res.end();
res.finished // => true

<readonly> headers :Object

HTTP response headers, following Node.js convention

Type:
  • Object
Example
res.set('content-type', 'text/plain')
   .set('set-cookie', 'foo=123; Expires=Sun, 1-Jan-2017 00:00:00 GMT; Path=/; Domain=foo.com')
   .set('x-foo', ['bar', 'baz']);
res.headers
// => {
//   'content-type': 'text/plain',
//   'set-cookie': ['foo=123; Expires=Sun, 1-Jan-2017 00:00:00 GMT; Path=/; Domain=foo.com'],
//   'x-foo': 'bar, baz'
// }

<readonly> statusCode :number

HTTP response status code

Type:
  • number
Example
res.status(404);
res.statusCode // => 404

Methods


append(field [, value])

Appends a given value to the HTTP response header field. If the header field is not already set, it creates the header with the given value.

Parameters:
Name Type Argument Description
field string | Object

Header field name or an object containing a key-value mapping of header fields.

value string | Array.<string> <optional>

Header value or a list of values

Returns:

this

Type
Response
Example
res.append('Content-Type', 'text/plain');
res.append({
  'Content-Type': 'text/plain',
  Pragma: 'no-cache'
});
res.append('X-Foo', ['bar', 'baz']);

clearCookie(name [, options])

Clears the cookie by the given name.

Parameters:
Name Type Argument Description
name string

Cookie name

options object <optional>

Options. See options parameter for res.cookie().

Returns:

this

Type
Response
Example
res.cookie('remember', '1', { path: '/' });
res.clearCookie('remember', { path: '/' });

Sets a cookie by adding a Set-Cookie header. The value paramter can either be a string or an object which can be represented as JSON.

To clear a cookie, use res.clearCookie(). undefined, null, false, and empty string ("") are valid values for the value parameter.

Options:
Property Type Default Value Description
domain string Not set Domain name where cookie is valid
encode function encodeURIComponent Function to be used to encode value
expires Date Not set Expiration date
httpOnly boolean false Make cookie visible only by the backend web app, and not by JavaScript
maxAge number Not set Number of milliseconds after which the cookie will be expired
path string "/" Path where cookie is valid
sameSite boolean | string false Disable third-party usage of cookie (allowed values: true / false / "lax" / "strict")
secure boolean false Makes cookie valid only with HTTPS
signed boolean false Whether cookie should be signed. The secret is derived from cookieParser(secret) middleware.
Parameters:
Name Type Argument Description
name string

Cookie name

value *

Cookie value

options Object <optional>

Options

Returns:

this

Type
Response
Example
res.cookie('remember', '1', { expires: new Date(Date.now() + 60 * 60 * 24 * 7 * 1000), httpOnly: true });
// If a non-string is passed, it is serialized as JSON for you.
res.cookie('seen', { ids: [1, 2, 3] }, { maxAge: 86400000 });
// The following requires a secret signing key to be passed to `cookieParser(secret)` middleware.
res.cookie('username', 'pete', { domain: '.example.com', path: '/', secure: true, signed: true });

end( [data] [, encoding] [, callback])

Sends an HTTP response. This function is usually invoked without any arguments to quickly respond without any data. To respond with data, you should use res.send() or res.json() instead.

Parameters:
Name Type Argument Description
data string | Buffer <optional>

data to write

encoding string <optional>

encoding to use when data is a string

callback function <optional>

callback to be invoked after the response is sent

Returns:

true if response is sent

Type
boolean

get(field)

Returns the value of the HTTP response header by a given field. The match is not case-sensitive.

Parameters:
Name Type Description
field string

Header field name

Returns:

value of the header

Type
string | Array.<string>

json( [body])

Sends an HTTP response with JSON body. The parameter will be converted to JSON with JSON.stringify() function.

Parameters:
Name Type Argument Description
body * <optional>

Data to be represented as JSON in the response body

Returns:

this

Type
Response
Example
res.json({ some: 'json' });
res.status(500).send({ error: 'something went wrong' });

jsonp( [body])

Sends an HTTP response with JSON body, optionally wrapped with JSONP callback.
The default query string param for JSONP callback name is callback. It can be overridden with the jsonp callback name setting.
If the callback name is not specified in the query string params, the behavior of this method is identical to res.json().

Parameters:
Name Type Argument Description
body * <optional>

Data to be represented as JSON in the response body

Returns:

this

Type
Response
Example
// ?callback=foo
res.jsonp({ data: "hello world" });
// => foo({ "data": "hello world" });

app.set('jsonp callback name', 'cb');
// ?cb=handle
res.status(500).jsonp({ error: 'something went wrong' });
// => handle({ "error": "something went wrong" });

location(url)

Sets the Location HTTP response header to the given url parameter.
If url is "back", it uses the value of the Referer in the request header unless the it is absent, in which case it will use the value "\".

Parameters:
Name Type Description
url string

URL/Path to be assigned to the Location header

Returns:

this

Type
Response
Example
res.location('/hello/world');
res.location('https://www.example.com/');
res.location('back');

redirect( [statusCode], url)

Sends a redirect response to the given url. If status is not specified, the default status of 302 Found is used.
If url is "back", it uses the value of the Referer in the request header unless the it is absent, in which case it will use the value "\".

Parameters:
Name Type Argument Description
statusCode status <optional>

HTTP status code

url string

URL/Path to be assigned to the Location header

Returns:

this

Type
Response
Example
res.redirect('/hello/world');
res.redirect('https://www.example.com/');
res.redirect(301, '/hello/world');
res.redirect('back');

removeHeader(field)

Removes the HTTP response header field.

Parameters:
Name Type Description
field string

Header field name

Returns:

this

Type
Response
Example
res.removeHeader('Content-Type');

send( [body])

Sends an HTTP response.

Parameters:
Name Type Argument Description
body string | boolean | number | Object | Array | Buffer <optional>

Response body

Returns:

this

Type
Response
Example
res.send({ some: 'json' });
res.send([ { foo: 1 }, { foo: 2 } ]);
res.send('Hello world!');
res.send(new Buffer('foobar'));
res.status(404).send({ error: 'not_found' });
res.status(500).send('something went wrong');

sendStatus(statusCode)

Sends an HTTP response with a given status code and the JSON representation of the status code as the response body.

Parameters:
Name Type Description
statusCode number

Status code

Returns:

this

Type
Response
Example
res.sendStatus(200); // equivalent to res.status(200).send({ status: 'OK' });
res.sendStatus(403); // equivalent to res.status(403).send({ status: 'Forbidden' });
res.sendStatus(404); // equivalent to res.status(404).send({ status: 'Not Found' });
res.sendStatus(500); // equivalent to res.status(404).send({ status: 'Internal Server Error' });

set(field [, value])

Sets the HTTP response header field to value. It replaces any existing value for the given field. To append rather than to replace, use res.append(). To set multiple fields at once, pass an object.

Parameters:
Name Type Argument Description
field string | Object

Header field name or an object containing a key-value mapping of headers.

value string | Array.<string> <optional>

Header value or a list of values

Returns:

this

Type
Response
Example
res.set('Content-Type', 'text/plain');
res.set({
  'Content-Type': 'text/plain',
  Pragma: 'no-cache'
});
res.set('X-Foo', ['bar', 'baz']);

status(code)

Sets the HTTP response status code.

Parameters:
Name Type Description
code number

HTTP status code

Returns:

this

Type
Response
Example
res.status(200).send({ status: 'ok' });

type(type)

Sets the Content-Type HTTP header. Known values for the type parameter are html, js, json, and text. If the type parameter passed contains the / character, it sets the Content-Type to type.

Parameters:
Name Type Description
type string

type of the response body

Returns:

this

Type
Response
Example
res.type('html');      // => 'text/html'
res.type('text/html'); // => 'text/html'
res.type('.html');     // => 'text/html'
res.type('json');      // => 'application/json'
res.type('png');       // => 'image/png'