Properties of the Request and Response Objects from Node+Express

Setting up an Express server is relatively easy and so many use it for full-stack applications. When building a web server and/or creating a full-stack application with Express, most of your actions would involve sending requests and receiving responses and the Request and Response objects enable us to do that. In this article, we'll be examining the various properties and methods of these objects as provided by Express.

If you are wondering why I am writing this, it is because I came across several errors during my Capstone project for She Code Africa Mentorship Program - Cohort 3. These errors could have been avoided if I had a better understanding of the properties we would be learning together.

Request handlers

Request handlers are the functions that handle the client request and construct a response. An example is shown below:

const handler = (req, res, next) => {
//code here
}

Properties of the Request Object

The request object is passed as the first parameter of a request handler. You can name it however you want but it common to name it req or request. All methods below are added by Express, except for req.headers and req.URL which originate in Node.

req.params

An array containing the named route parameters. For example, if you have the route /user/:name, then the "name" property is available as req.params.name

req.query

An object containing querystring parameters as name/value pairs

req.body

An object containing POST parameters. POST parameters are passed in the body of the request, unlike querystring parameters which are passed in the URL. To access the contents of req.body, you'll need middleware that can parse the body content type such as body-parser.

req.route

A string showing the current route

req.cookies/req.signedCookies

Objects containing cookie values passed from the client. Requires a middleware that can parse the cookie content type such as cookie-parser.

req.headers

An object containing the request headers where the header names are the keys and the header values are the values. Remember that this comes from Node and would not be listed in the Express documentation.

req.accepts(types)

A method to determine whether the client accepts a give type or types. The value of this method can be a single MIME type such as application/JSON, a comma-delimited list or an array.

req.ip

The IP address of the client

req.path

The request path. This is without protocol, host, port or querystring.

req.hostname

A method that returns the hostname reported by the client. This information can be spoofed and should not be used for security purposes.

req.xhr

A Boolean value that returns true if the request originated from an Ajax call.

req.protocol

The protocol used in making this request. An example is HTTP or HTTPS.

req.secure

A convenience property that returns true if the connection is secure. This is equivalent to req.protocol === 'https'.

req.url/req.originalUrl

These properties return the path and querystring (they do not include protocol, host, or port). req.URL can be rewritten for internal routing purposes, but req.originalUrl is designed to retain the original request and querystring.

Properties of the Response Object

The Response object (res) specifies the HTTP response which is sent by an Express app when it gets an HTTP request. It is passed as the second parameter of a request handler. You can also name it however you want but it common to name it res or response. It begins as an instance of http.ServerResponse which is a core Node object. All methods below are added by Express.

res.status(code)

Sets the HTTP status code. By default, this is 200 (OK), so it is used to return any other status code you want to use. For redirects (status codes 301, 302, 303, and 307), it is better to use the method redirect. res.status returns the full response object, meaning you can chain calls like this:

res.status(404).send('Not found')

res.set(name, value)

Sets a response header. This is not something you will normally be doing manually. You can also set multiple headers at once by passing a single object argument whose keys are the header names and whose values are the header values.

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

Sets or clears cookies that will be stored on the client.

res.redirect([status], url)

Redirects the browser. The default redirect code is 302 (Found). In general, you should minimize redirection unless you are permanently moving a page, in which case you should use the code 301 (Moved Permanently).

res.send(body)

Sends a response to the client. Express defaults to a content type of text/html, so if you want to change it to text/plain (for example), you’ll have to call res.type('text/plain’) before calling res.send. If body is an object or an array, the response is sent as JSON and it is better to use res.json.

res.json(json)

Sends JSON to the client.

res.jsonp(json)

Sends JSONP to the client.

res.end()

Ends the connection without sending a response.

res.type(type)

This method sets the content-type HTTP header to the MIME type. It is equivalent to res.set(\'Content-Type ', type), except that it will also attempt to map file extensions to an internet media type if you provide a string without a slash in it. For example, res.type('html ') will result in a Content-Type of text/html. Generally, it is better to use res.set().

res.format(object)

This method allows you to send different content depending on the Accept request header.

res.format({'text/plain': 'hi there', 'text/html': '<b>hi there</b>'})

res.attachment([filename]), res.download(path, [filename], [callback])

Both of these methods set a response header called Content-Disposition to attachment; this will prompt the browser to download the content instead of displaying it in a browser. You may specify filename as a hint to the browser. With res.download, you can specify the file to download, whereas res.attachment just sets the header and you still have to send content to the client.

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

This method will read a file specified by path and send its contents to the client. However, it’s easier to use the static middleware and put files you want available to the client in the public directory.

Sets the Links response header. This is a specialized header that has little use in most applications.

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

res.locals is an object containing default context for rendering views. res.render will render a view using the configured templating engine (the locals parameter to res.render shouldn’t be confused with res.locals: it will override the context in res.locals, but context not overridden will still be available). Note that res.render will default to a response code of 200.

Conclusion

You will most likely never have to use all of the above properties. Despite this, it is very helpful to have knowledge of these at the back of your mind.

Do leave comments and reviews below.