Monday, June 8, 2020

ExpressJS Response Object

ExpressJS Response Object


The response object is generally represented by res, represents the HTTP response that an Express application sends whenever an HTTP request is received.

The general syntax of a callback function is,

app.get('/', function (req, res) { 
// res represents the response object 
// Write code here 
}); 

The request object has many properties and methods.

Properties


res.app


res.app has a reference to the instance of the ExpressJS application that is using the middleware.

res.headersSent


res.headerSent represents a boolean property that shows if the app sent HTTP headers for the response.

res.locals


It provides an object containing the response local variables having request level scope.


Methods


res.append(field [, value])


We can append the provided value (a string or array) to the HTTP response header field. The header will be created if it set yet.

res.append('Link', ['<http://localhost/>', '<http://localhost:3000/>'])
res.append('Set-Cookie', 'name=steve; Path=/; HttpOnly')

res.attachment([filename]) 


This method is used to set the HTTP response Content-Disposition header field to “attachment” (by default). If a filename is provided, then it will set the Content-Type based on the extension name using res.type() and sets the Content-Disposition “filename=” parameter.

res.attachment()
// Content-Disposition will be set as attachment

res.attachment('path/to/pic.png')
// Content-Disposition: attachment; filename="pic.png"
// Content-Type: image/png

res.cookie(name, value [, options]) 

This method can is used to set the cookie name to value. The value parameter can be a string or object converted to JSON.

res.clearCookie(name [, options]) 

It can be used to clear the cookie described by name.

res.download(path [, filename] [, options] [, fn]) 

It can be used to transfer the file at the path as an “attachment” (downloading). Generally, the browser prompts the user to download. By default, the Content-Disposition header “filename=” parameter is a path (this typically appears in the browser dialog).

res.download('/file-12345.pdf')

res.download('/file-12345.pdf', 'file.pdf')

res.download('/file-12345.pdf', 'file.pdf', function (err) {
  if (err) {
    // Handle the error
  } else {
    // decrement a download credit, etc.
  }
});

res.end([data] [, encoding]) 


res.end() method ends the response process.

res.format(object) 


This method operates content-negotiation on the Accept HTTP header, request header is available. req.accepts() method is used to select a handler for the request, on the basis of acceptable types ordered by their quality values. If the header is not available, the first callback is executed. When no match is found, the server replies with 406 “Not Acceptable”, or calls the default callback.

res.get(field) 


This method returns the HTTP response header given by the field in a case-insensitive manner.

res.get('Content-Type')

res.json([body]) 


It is used to send a JSON response with the right content-type. The parameters are converted to a JSON string using JSON.stringify().

res.links(links) 

We can join the links specified as properties of the parameter to fill the response’s Link HTTP header field.

res.links({
  prev: 'http://www.example.com/name?page=2',
  next: 'http://www.example.com/name?page=15'
});

res.redirect([status,] path)


The response can be redirected to the URL derived from the given path and with given status(a positive integer that represents an HTTP status code ). If not provided, the default status is 302, which means “Found”.

res.redirect('http://www.example1.com');
res.redirect(301, 'http://www.example2.com');

res.render(view [, locals] [, callback])


It is used to render a view and sends the rendered HTML string to the client. The optional parameters are,

locals, local variables for the view.

Callback is a callback function. If mentioned, the method returns both the possible error and rendered string but does not perform an automated response. When an error occurs, the method invokes the next(err) internally.

res.render('user', { name: 'Tobi' }, function (err, html) {
  // ...
});

res.send([body])


Sends the response

res.send('<p>write html</p>')

res.sendFile(path [, options] [, fn]) 

It is used to transfer the file at the specified path. This method sets the Content-Type response HTTP header field on the basis of the filename’s extension. Unless the root option is set in the options object, the path must be an absolute path to the file.

res.sendStatus(statusCode) 


It is used to set the response HTTP status code to statusCode and send its string representation as to the response body.

for example,
res.sendStatus(200) // equivalent to res.status(200).send('OK')

res.set(field [, value])

Thi method sets the response’s HTTP header field to value.


res.type(type)


This method sets the Content-Type HTTP header to the MIME type as describes by mime.lookup() for the provided type. If type contains the “/” character, then it sets the Content-Type to type.