Hello folks! welcome back to a new edition of our tutorial on Node.js. In this section of our tutorial on Node.js, we will be studying about Node.js Response Object.
The Node.js res object represents the HTTP response that an Express application sends when it gets an HTTP request.
The Node.js res object represents the HTTP response that an Express application sends when it gets an HTTP request.
Response Object Properties
The following table below is the list of a few properties associated with response object -
Sr.No. | Properties & Description |
---|---|
1 | res.app This property holds a reference to the instance of the express application that is using the middleware. |
2 | res.headersSent Boolean property that indicates if the app sent HTTP headers for the response. |
3 | res.locals An object that contains response local variables scoped to the request |
READ: Node.js | Request Object
Response Object Methods
res.append(field [, value])
res.append(field [, value])
This method appends the specified value to the HTTP response header field.
Example
Following below is a simple example -
res.append('Link', ['<http://localhost/>', '<http://localhost:3000/>']); res.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly'); res.append('Warning', '199 Miscellaneous warning');
res.attachment([filename])
res.attachment([filename])
This method is used for sending a file as an attachment in the HTTP response.
Example
Following below is a simple example -
res.attachment('path/to/logo.png');
res.cookie(name, value [, options])
res.cookie(name, value [, options])
This method is used to set cookie name to value. The value parameter may be a string or object converted to JSON.
Example
Following below is a simple example -
res.cookie('name', 'tobi', { domain: '.example.com', path: '/admin', secure: true }); res.cookie('cart', { items: [1,2,3] }); res.cookie('cart', { items: [1,2,3] }, { maxAge: 900000 });
res.clearCookie(name [, options])
res.clearCookie(name [, options])
This method clears the cookie specified by name.
Example
Following below is a simple example -
res.cookie('name', 'tobi', { path: '/admin' }); res.clearCookie('name', { path: '/admin' });
res.download(path [, filename] [, fn])
res.download(path [, filename] [, fn])
This method is used for transferring the file at path as "attachment". Typically browsers will prompt the user for download.
Example
Following below is a simple example -
res.download('/report-12345.pdf'); res.download('/report-12345.pdf', 'report.pdf'); res.download('/report-12345.pdf', 'report.pdf', function(err){ });
res.end([data] [, encoding])
res.end([data] [, encoding])
This method ends the response process.
Example
Following below is a simple example -
res.end(); res.status(404).end();
READ: Node.js | File System
res.format(object)
res.format(object)
This method performs content-negotiation on the Accept HTTP header on the request object, when present.
Example
Following below is a simple example -
res.format ({ 'text/plain': function() { res.send('hey'); }, 'text/html': function() { res.send('hey'); }, 'application/json': function() { res.send({ message: 'hey' }); }, 'default': function() { // log the request and respond with 406 res.status(406).send('Not Acceptable'); } });
res.get(field)
res.get(field)
The res.get(field) method returns the HTTP response header specified by field.
Example
Following below is a simple example -
res.get('Content-Type');
res.json([body])
res.json([body])
This method sends a JSON response -
Example
Following below is a simple example -
res.json(null) res.json({ user: 'tobi' }) res.status(500).json({ error: 'message' })
res.jsonp([body])
res.jsonp([body])
This method sends a JSON response with JSONP support.
Example
Following below is a simple example -
res.jsonp(null) res.jsonp({ user: 'tobi' }) res.status(500).jsonp({ error: 'message' })
res.links(links)
res.links(links)
This method is used to join the links given as properties of the parameter to populate the response's Link HTTP header field.
Example
Following below is a simple example -
res.links ({ next: 'http://api.example.com/users?page=2', last: 'http://api.example.com/users?page=5' });
res.location(path)
res.location(path)
The res.location(path) method is used to set response Location HTTP header field based on the specified path parameter.
Example
Following below is a simple example -
res.location('/foo/bar'); res.location('foo/bar'); res.location('http://example.com');
READ: Node.js | Domain Module
res.redirect([status,] path)
res.redirect([status,] path)
res.redirect([status,] path) method redirects the url derived from the specified path, with specified HTTP status code status.
Example
Following below is a simple example -
res.redirect('/foo/bar'); res.redirect('http://example.com'); res.redirect(301, 'http://example.com');
res.render(view [, locals] [, callback])
res.render(view [, locals] [, callback])
This method renders a view and sends the rendered HTML string to the client.
Example
Following below is a simple example -
// send the rendered view to the client res.render('index'); // pass a local variable to the view res.render('user', { name: 'Tobi' }, function(err, html) { // ... });
res.send([body])
res.send([body])
This method sends the HTTP response.
Example
Following below is a simple example -
res.send(new Buffer('whoop')); res.send({ some: 'json' }); res.send('<p>some html</p>');
res.sendFile(path [, options] [, fn])
res.sendFile(path [, options] [, fn])
This method is used for transferring the file at the specified path. This method sets the "Content-Type" response HTTP header field based on the filename's extension.
Example
Following is a simple example -
res.sendFile(fileName, options, function (err) { // ... });
res.sendStatus(statusCode)
res.sendStatus(statusCode)
This method is used to set response HTTP status code to statusCode and then sends its string representation as response body.
Example
Following below is a simple example -
res.sendStatus(200); // equivalent to res.status(200).send('OK') res.sendStatus(403); // equivalent to res.status(403).send('Forbidden') res.sendStatus(404); // equivalent to res.status(404).send('Not Found') res.sendStatus(500); // equivalent to res.status(500).send('Internal Server Error')
res.set(field [, value])
res.set(field [, value])
This method is used to set the response's HTTP header field to value.
Example
Following below is a simple example -
res.set('Content-Type', 'text/plain'); res.set ({ 'Content-Type': 'text/plain', 'Content-Length': '123', 'ETag': '12345' })
res.status(code)
res.status(code)
This method is used to set the HTTP status for the response.
Example
Following below is a simple example -
res.status(403).end(); res.status(400).send('Bad Request'); res.status(404).sendFile('/absolute/path/to/404.png');
res.type(type)
res.type(type)
This method sets the Content-Type HTTP header to the MIME type.
Example
Following below is a simple example -
res.type('.html'); // => 'text/html' res.type('html'); // => 'text/html' res.type('json'); // => 'application/json' res.type('application/json'); // => 'application/json' res.type('png'); // => image/png:
READ: Node.js | Console
Alright guys! This is where we are going to be rounding up for this tutorial. In our next tutorial, we will be studying about Node.js RESTful API.
Feel free to ask your questions where necessary and we will attend to them as soon as possible. If this tutorial was helpful to you, you can use the share button to share this tutorial.
Follow us on our various social media platforms to stay updated with our latest tutorials. You can also subscribe to our newsletter in order to get our tutorials delivered directly to your emails.
Thanks for reading and bye for now.
Feel free to ask your questions where necessary and we will attend to them as soon as possible. If this tutorial was helpful to you, you can use the share button to share this tutorial.
Follow us on our various social media platforms to stay updated with our latest tutorials. You can also subscribe to our newsletter in order to get our tutorials delivered directly to your emails.
Thanks for reading and bye for now.