Express js Response

This is the HTTP response, send back by Express.js to the client machine.

These are the list of some properties of the response object.

res.attachment()

The res.attachment() sends an outgoing download file in the response to the user agent.

res.attachment('filename');

res.cookie()

The res.cookie() with name and value pairs send back to the client machine along with the response.

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

To use cookies in express, we will require cookie-parser middleware.


res.get()

The res.get() contains the string value of the response header for a passed header type.

res.get('Content-Type');

res.set()

The res.set() method is an alias of res.header() and serves as a wrapper for the Node.js http core module's response.setHeader(). The main difference is that res.set() is smart enough to call itself recursively when we pass multiple header-value pairs to it in the form of an object.

res.set('Content-type', 'text/html');

res.status()

The res.status() sets the status code of this response.

res.status(200).send('Hello World');

res.send()

The res.send() method lies somewhere between high-level res.render() and low-level res.end(). The res.send() sends a string response in a format of XML, CSV, plain text etc.

res.send(200, {message: 'Data sent successfully.'});

res.json()

The res.json() method is used to send JSON data. It is equivalent to res.send() when an object or array is passed. By default, the header Content-Type is set to application/json.

app.get('/json', function(req, res) {
 res.json(200, [{name: 'Smith', department: 'CS'},
 {name: 'John', department: 'IT'},
 {name: 'mary', department: 'IT'}
 ]);
});




Read more articles


General Knowledge



Learn Popular Language