Node.js http Module

Java FileNode.js Built-in Modules


Node.js'shttpThe module is one of the core built-in modules of Node.js. It allows developers to create HTTP servers and clients. Through this module, we can easily handle HTTP requests and responses, and build web applications or API services.

httpThe module provides the ability to create servers and make HTTP requests, and is the foundation for building web applications. It supports the HTTP/1.1 protocol and provides a rich API for handling various HTTP-related operations.


Create an HTTP Server

UsehttpThe module makes it very simple to create a server. Below is a basic example:

Example

const http = require('http');

// Create an HTTP server
const server = http.createServer((req, res) => {
  // Set response headers
  res.writeHead(200, {'Content-Type': 'text/plain'});
 
  // Send response data
  res.end('Hello, World!\n');
});

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

Code Explanation

  1. require('http')- Import Node.js's http module
  2. http.createServer()- Create an HTTP server instance
  3. Callback function(req, res) => {...}- Handle each HTTP request
    • req- Request object, contains request information sent by the client
    • res- Response object, used to send responses to the client
  4. res.writeHead()- Set response headers
  5. res.end()- End the response and send data
  6. server.listen()- Start the server and listen on the specified port

Handling HTTP Requests

An HTTP server needs to be able to handle different types of requests. Let's see how to parse request information:

Example

const http = require('http');

const server = http.createServer((req, res) => {
  // Get request method, URL, and request headers
  const { method, url, headers } = req;
 
  // Log request information
  console.log(`Received ${method}request, path: ${url}`);
  console.log('Request headers:', headers);
 
  // Handle based on request method
  if (method === 'GET') {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('This is a GET request\n');
  } else if (method === 'POST') {
    let body = '';
   
    // Collect POST data
    req.on('data', chunk => {
      body += chunk;
    });
   
    // Data reception complete
    req.on('end', () => {
      console.log('POST data:', body);
      res.writeHead(200, {'Content-Type': 'text/plain'});
      res.end('Data received\n');
    });
  } else {
    res.writeHead(405, {'Content-Type': 'text/plain'});
    res.end('Method not allowed\n');
  }
});

server.listen(3000);

Common Properties of the Request Object (req)

  • req.method: HTTP request method (GET, POST, PUT, DELETE, etc.)
  • req.url: The URL path of the request
  • req.headers: Request headers object
  • req.httpVersion: HTTP protocol version

Common Methods of the Response Object (res)

  • res.writeHead(statusCode, headers): Set response status code and headers
  • res.write(data): Write response body
  • res.end([data]): End the response, optionally send final data
  • res.setHeader(name, value): Set response headers

Making HTTP Requests

httpThis module can not only create servers, but also act as a client to make HTTP requests:

Example

const http = require('http');

// Make a GET request
http.get('http://jsonplaceholder.typicode.com/posts/1', (res) => {
  let data = '';
 
  // Receive data
  res.on('data', (chunk) => {
    data += chunk;
  });
 
  // Data reception complete
  res.on('end', () => {
    console.log('Response data:', JSON.parse(data));
  });
}).on('error', (err) => {
  console.error('Request error:', err);
});

Making a POST Request

Example

const http = require('http');

// Request options
const options = {
  hostname: 'jsonplaceholder.typicode.com',
  port: 80,
  path: '/posts',
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  }
};

// Create request
const req = http.request(options, (res) => {
  let data = '';
 
  res.on('data', (chunk) => {
    data += chunk;
  });
 
  res.on('end', () => {
    console.log('Response:', JSON.parse(data));
  });
});

// Handle errors
req.on('error', (err) => {
  console.error('Request error:', err);
});

// Write request data
const postData = JSON.stringify({
  title: 'foo',
  body: 'bar',
  userId: 1
});

req.write(postData);
req.end();

Practical Application Scenarios

1. Creating a RESTful API

Example

const http = require('http');

const server = http.createServer((req, res) => {
  const { method, url } = req;
 
  // Simple route handling
  if (method === 'GET' && url === '/api/users') {
    res.writeHead(200, {'Content-Type': 'application/json'});
    res.end(JSON.stringify([{id: 1, name: 'Alice'}, {id: 2, name: 'Bob'}]));
  } else if (method === 'POST' && url === '/api/users') {
    let body = '';
    req.on('data', chunk => body += chunk);
    req.on('end', () => {
      const newUser = JSON.parse(body);
      // Data can be saved to the database here
      res.writeHead(201, {'Content-Type': 'application/json'});
      res.end(JSON.stringify({id: Date.now(), ...newUser}));
    });
  } else {
    res.writeHead(404, {'Content-Type': 'text/plain'});
    res.end('Not Found\n');
  }
});

server.listen(3000);

2. Proxy Server

Example

const http = require('http');

const proxy = http.createServer((clientReq, clientRes) => {
  // Make a request to the target server
  const options = {
    hostname: 'example.com',
    port: 80,
    path: clientReq.url,
    method: clientReq.method,
    headers: clientReq.headers
  };
 
  const proxyReq = http.request(options, (proxyRes) => {
    // Forward the target server's response to the client
    clientRes.writeHead(proxyRes.statusCode, proxyRes.headers);
    proxyRes.pipe(clientRes);
  });
 
  // Forward the client request body
  clientReq.pipe(proxyReq);
});

proxy.listen(8080);

Best Practices

  1. Error handling: Always handle error events in requests and responses
  2. Performance considerations: For high-concurrency applications, consider using connection pools
  3. Security:
    • Validate all inputs
    • Set appropriate security headers
    • Limit request body size to prevent DoS attacks
  4. Use streams: For large file transfers, use streaming
  5. Consider frameworks: For complex applications, consider using frameworks such as Express and Koa

Summary

Node.js'shttpThe module provides the basic capability to build network applications. Although there are many more advanced frameworks available now, understandinghttpthe working principles of the module is crucial for any Node.js developer. By mastering this core module, you can better understand how web applications work, and be able to build custom solutions according to your needs.

Java FileNode.js Built-in Modules

Other Extensions