HTTP

HTTP (Hypertext Transfer Protocol) is an application-layer protocol used for transmitting hypermedia documents, such as HTML. It is the foundation of data communication on the World Wide Web, enabling web browsers and servers to communicate and exchange information.

HTTP is a request-response protocol where a client (usually a web browser) sends a request to a server, which then responds with the requested resource or an appropriate status message. The protocol defines methods for various types of actions, status codes to indicate the result of a request, and headers for passing additional information.

HTTP Methods:

Examples of HTTP Requests:

  1. GET Request:

    GET /index.html HTTP/1.1
    Host: www.example.com
    

    This request asks the server to return the content of the “index.html” page.

  2. POST Request:

    POST /submit-form HTTP/1.1
    Host: www.example.com
    Content-Type: application/x-www-form-urlencoded
    Content-Length: 27
    
    username=johndoe&password=1234
    

    This request sends form data (username and password) to the server for processing.

Example of Using HTTP in JavaScript:

// Using Fetch API to make a GET request
fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

// Using Fetch API to make a POST request
fetch('https://api.example.com/submit', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({ username: 'johndoe', password: '1234' })
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));

Status Codes: