Sending Responses (res object) in Node.js 🎯

beginner
13 min

Sending Responses (res object) in Node.js 🎯

Welcome to another exciting lesson on Node.js at CodeYourCraft! Today, we'll dive into one of the most fundamental aspects of Node.js - sending responses using the res object. This knowledge is essential for creating dynamic and interactive web applications.

Understanding the res object 📝

The res object in Node.js is a built-in object that stands for "response". It's used to send data back to the client (usually a web browser) in response to a client's request.

Sending Simple Responses 💡

Let's start with the simplest form of sending a response - a text message.

javascript
const http = require('http'); const server = http.createServer((req, res) => { res.end('Hello, World!'); // Sending a simple text response }); server.listen(3000, () => { console.log('Server is running on port 3000'); });

In this example, we create an HTTP server, and when a client makes a request, we respond with the text 'Hello, World!'.

The statusCode Property 💡

HTTP responses consist of a status code, a status message, and the response body. The statusCode property in the res object is used to set the status code of the HTTP response.

javascript
const http = require('http'); const server = http.createServer((req, res) => { res.statusCode = 200; res.setHeader('Content-Type', 'text/plain'); res.end('Hello, World!'); }); server.listen(3000, () => { console.log('Server is running on port 3000'); });

In this example, we set the status code to 200 (OK), and we also set the Content-Type header to text/plain, which tells the client that the response body is plain text.

The json() Method 💡

To send JSON responses, Node.js provides the json() method. This method automatically sets the Content-Type header to application/json and converts the provided JavaScript object into a JSON string.

javascript
const http = require('http'); const data = { message: 'Hello, World!' }; const server = http.createServer((req, res) => { res.statusCode = 200; res.json(data); }); server.listen(3000, () => { console.log('Server is running on port 3000'); });

In this example, we create a JavaScript object data and send it as a JSON response.

Quiz Time 🎯

Quick Quiz
Question 1 of 1

What is the purpose of the `res` object in Node.js?

Wrapping Up 📝

In this lesson, we learned about sending responses using the res object in Node.js. We covered sending simple text responses, setting the status code, and using the json() method to send JSON responses.

In the next lesson, we'll dive deeper into handling client requests and understanding middleware in Node.js. Until then, keep coding and happy learning! 🚀