Sending Response

In Node.js, you can send a response to a client using the response object, which is provided as a parameter to the request handler function. The following is an example of sending a simple text response:

const http = require('http');

const server = http.createServer((req, res) => {
  res.end('Hello World!');
});

server.listen(3000, () => {
  console.log('Server running on port 3000');
});

In this example, a HTTP server is created using the http module, and the response is sent using the res.end() method.

You can also send JSON data in the response, as shown in the following example:

const http = require('http');

const server = http.createServer((req, res) => {
  res.end(JSON.stringify({ message: 'Hello World!' }));
});

server.listen(3000, () => {
  console.log('Server running on port 3000');
});

In this example, the response headers indicate that the content type is application/json, and the response body is a JSON-encoded string that represents a simple message.

Last updated