Bootcamp
Search…
📅
Course Schedule
0: Language and Tooling Teaching Guide
1: Frontend Basics Teaching Guide
2: Backend Basics Teaching Guide
3: Backend Applications Teaching Guide
4: Backend Structure Teaching Guide
5: Full-Stack Applications Teaching Guide
6: Frontend Infrastructure Teaching Guide
7: React Teaching Guide
8: Advanced React Teaching Guide
9: Advanced Topics Teaching Guide
🧮
Algorithms Teaching Guide
💼
Interview Prep Teaching Guide
☺
User Experience Teaching Guide
2.9: HTTP Requests and Responses

Introduction

​HTTP stands for Hypertext Transfer Protocol, a protocol that determines how data is sent across the Internet through HTTP Requests and Responses. HTTP is an "application-level" protocol, meaning it packages data to be sent before lower-level protocols such as TCP/IP translate and transmit that data in the form of "packets".

What is a Server

According to Wikipedia, a server is "a piece of computer hardware or software that provides functionality for other programs or devices, called 'clients'". In the context of building apps, this means software that listens for requests from "clients" (e.g. browsers or mobile apps) over the Internet, and sends back relevant responses (e.g. HTML or app data). Servers are typically running 24/7 waiting for requests, such that clients can access their functionality 24/7.
Computers send HTTP requests to servers over Internet, and servers may respond with HTTP responses.

Example Server

Let's create a server with Node. Node has a built-in global http module with a createServer function that creates an http.Server object (instance of a Server class defined in the http module). This server object has built-in server functionality like the listen method that starts the server listening on a given port. When this server receives a request, it responds with "Yay!".

index.js

1
// createServer comes from the http module built-in to Node.
2
import { createServer } from 'http';
3
​
4
const handleIncomingRequest = (request, response) => {
5
console.log('Received request!');
6
​
7
// response.end tells the server to send the completed response and mark
8
// this request-response interaction complete.
9
// https://nodejs.org/api/http.html#http_response_end_data_encoding_callback
10
response.end('Yay!', 'utf-8');
11
};
12
​
13
// createServer creates the server object. It accepts a request listener function.
14
// The server calls the function every time it receives a request.
15
// The listen method tells server to start listening for requests on given port.
16
createServer(handleIncomingRequest).listen(3004);
Copied!

Sample Command

1
node index.js
Copied!
This server is available at: http://localhost:3004. localhost is the default domain name for all servers running on our local machines, e.g. in our terminal programs. The port is specified from within the server application code, e.g. index.js above. We avoid port 80 to prevent port conflicts between this server and other apps potentially running on localhost.
Note that when we run index.js the server runs indefinitely. It waits for incoming requests until we terminate the program with Ctrl+C, which sends an interrupt signal to the process. When the server is running, look for the running process in Task Manager (Windows) or Activity Monitor (Mac).

Requests Always Asynchronous

Our programs (both clients and servers) can and should assume that retrieving data from the Internet will be slow and unpredictable because of the following reasons.
  1. 1.
    Data will need to travel long distances (e.g. across the world)
  2. 2.
    Internet connections are unstable (think developing regions with low connectivity)
We always use asynchronous code when requesting data from the Internet, so that our programs do not hang while waiting for data, which could take an indefinite amount of time.
Retrieving data over 4G is like a round-trip to Saturn compared with retrieving data locally.
Hardware Component
What we use it for
Time
Relative Kilometers
Relative Distance
x Times Slower Than RAM
RAM Memory
var x = 0;
console.log(x);
0.0000001 seconds
1 km
Your office.
~
SSD Hard Drive
Databases, files on the computer.
0.00015 seconds
150,000km
Halfway to the moon.
10³
LAN Network
Networked Database access from a computer nearby.
0.15 seconds
150,000,000km
Twice the distance to Mars.
10⁸
4G Mobile Network
Downloading something on a mobile device (30 mbps).
1 second
1,000,000,000km
Not quite to Saturn.
10⁹

Request and Response Headers

Headers are meta information about HTTP requests and responses. There are many kinds of headers and we will review the ones relevant to us.

HTTP Request Method Header

The request "method" indicates the kind of action we are requesting from the server. The 4 most common methods are GET, POST, PUT, and DELETE, of which GET and POST are the most common. The method is a header included in the request so that the server can better interpret what we are asking of it.
  1. 1.
    GET is default and most common method, which represents retrieving data. We trigger GET requests when we enter URLs in the browser bar.
  2. 2.
    POST is the most common method for creating or "posting" data on/to the server.
  3. 3.
    PUT and DELETE methods are derivatives of POST, used to better identify requests where we wish to edit or delete data respectively.
It is often up to the app developer to decide which request method to use for which actions. Generally we use GET, POST, PUT, and DELETE requests for retrieving, creating, updating, and deleting data respectively.

HTTP Response Status Code Header

The response "status code" is a number that indicates the status of the request. HTTP responses almost always include a status code to let the client know if the request was successful, or why it might have been unsuccessful. Software engineers like us decide which status codes to include in HTTP responses to inform the client about their request.
200 is the status code that indicates success. Many of us may also be familiar with 404 (Not Found), or 403 (Forbidden). When sending responses, we should strive to provide the most precise status code for the given request. This page summarises HTTP status codes and what they represent.
In our example server built on the Node http module above, we can use the method writeHead to set the status code of each response. More on writeHead in the docs.
1
response.writeHead(200, {});
Copied!

How to Send Requests

In RA's Bootcamp we will primarily be sending requests from our frontend applications in Chrome, but requests can be sent from many applications for many reasons. For example, our OS's Software Update application may be requesting for updates. The Spotify app may be requesting for music data. We may be triggering test requests from our terminal via curl or in the Thunder Client app.

Send Request with Chrome

Type "rocketacademy.co" in the address bar and hit Enter.

Send Request from Command Line

curl is a command line program to make requests. See more curl examples here.
1
curl rocketacademy.co
Copied!

Send Request with Node.js

​get is a function from the built-in http module that sends a GET request to the specified URL. The following is code that might run in the client (e.g. browser).

Sample Request Code (Client)

1
import { get } from 'http';
2
​
3
const handleResponse = (response) => {
4
// Compile response data in a data variable.
5
// The response may contain multiple "chunks" of data.
6
let data = '';
7
​
8
// Add chunk of data to data var when each "chunk" is received.
9
response.on('data', (chunk) => {
10
data += chunk;
11
});
12
​
13
// We have received the whole response. Print the full response data.
14
response.on('end', () => {
15
console.log('Response Data: ', data);
16
});
17
};
18
​
19
// Send an HTTP GET request, handle response with handleResponse callback.
20
// Handle errors by logging the error message.
21
get('http://info.cern.ch/', handleResponse).on('error', (err) => {
22
console.error('Error: ' + err.message);
23
});
Copied!

Testing Servers Locally

  1. 1.
    When developing and testing applications, we almost always want to run both frontend and backend code locally (i.e. on the computer in front of us) first to speed up development by avoiding network latency.
  2. 2.
    Once we've started our server locally, we can send requests to it through its local IP address or domain name, 127.0.0.1 or localhost respectively.
  3. 3.
    Once our server code works locally, we can deploy it to the cloud so others can access the server.
Our computer hardware simulates that requests to localhost come from outside.

Exercise

  1. 2.
    Set up a server that listens for requests.
  2. 3.
    Make a GET request to your server.
  3. 4.
    Make a GET request to google.com.
  4. 5.
    Make a GET request to http://info.cern.ch/​
  5. 6.
    Use Chrome's Network tab to view your request details. Look for HTTP method and status code header details.
  6. 7.
    Set a response header of rocketacademy with value true in your server using the response.writeHead method (example above). Confirm you receive it in Chrome's Network tab after sending a request.
  7. 8.
    Set other status codes in the response header such as 206, 418 and 507. What do they do?
  8. 9.
    Set the special status code 301 like the following code snippet. What does it do? What do we see in the Network tab after receiving this response?
1
response.writeHead(301, { Location: 'http://info.cern.ch/' });
Copied!
Last modified 2mo ago