Logo

Developer learning path

Node.js

Request and Response Objects in Node.js

Request and Response Objects

73

#description

In Node.js, the Request and Response objects are used to handle the incoming HTTP request and outgoing HTTP response, respectively.

The Request object contains information about the incoming request, such as the URL, method, headers, and query parameters. It can also contain data from the request body, for example, if the request is a POST request with form data or JSON payload. The Request object can be accessed using the req keyword in your Node.js code.

The Response object, on the other hand, is used to construct the HTTP response that will be sent back to the client. It contains methods to set the response status code, headers, and the response body. The Response object can be accessed using the res keyword in your Node.js code.

Here is an example of a simple HTTP handler in Node.js that uses the Request and Response objects:

                    
const http = require('http');

const server = http.createServer((req, res) => {
  // Log the incoming request method and URL
  console.log(`${req.method} ${req.url}`);

  // Set the response status code and header
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');

  // Write the response body and end the response
  res.write('Hello, world!');
  res.end();
});

server.listen(3000, () => {
  console.log('Server listening on http://localhost:3000');
});
                  

In this example, we create a simple HTTP server and define a callback function to handle incoming requests. The req and res parameters are used to access the Request and Response objects, respectively. We log the incoming request method and URL to the console, set the response status code to 200 and the Content-Type header to text/plain, write the response body with the message "Hello, world!", and end the response.

Overall, the Request and Response objects provide a simple and powerful API for handling HTTP requests and responses in Node.js.

March 25, 2023

If you don't quite understand a paragraph in the lecture, just click on it and you can ask questions about it.

If you don't understand the whole question, click on the buttons below to get a new version of the explanation, practical examples, or to critique the question itself.