← Back

HTTP REQUESTS IN JAVASCRIPT

HTTP requests let frontend code communicate with servers and APIs.

This note explains HTTP requests in simple language.

You will learn:

  1. what a server is
  2. what backend means
  3. what an API is
  4. what a REST API is
  5. what a resource path or endpoint is
  6. what fetch() does
  7. how to inspect requests in the Network tab
  8. what response codes mean
  9. how to check response.ok
  10. what HTTP methods and headers are
  11. what CORS means

1. What is a server?

A server is a computer with special software that receives and processes requests from other devices on the network.

Easy definition:

Server = computer that listens, receives requests, and sends responses

Diagram 1. Server idea

Browser
-> sends request
Server
-> sends response
Browser receives data

When you open a website or request data, your browser usually talks to a server.

2. What is backend?

The backend is the program that runs on the server.

It:

Diagram 2. Backend job

Client request
-> backend receives it
-> backend processes data
-> backend sends response

The browser is usually the client. The backend is the logic on the server side.

3. What is an API?

API means:

Application Programming Interface

An API is a set of clearly defined rules that tells you:

Easy definition:

API = rules for talking to a program

Diagram 3. API idea

Client
-> asks according to rules
API
-> returns data/result
Client gets response

An API is like a menu of allowed actions. You ask in the correct format, and the server answers in the correct format.

4. What is a REST API?

A REST API is a backend built according to REST principles.

REST defines:

A REST API often acts as an intermediary between:

Instead of returning an HTML page, it usually returns JSON data.

Diagram 4. REST API flow

Client
-> HTTP request
REST API
-> works with database / logic
REST API
-> JSON response
Client

A normal website often returns HTML. A REST API usually returns structured data, most often JSON.

5. What is a resource?

A resource is the thing you want to work with.

Examples:

In REST APIs, resources are accessed through paths.

6. Resource path and endpoint

Requests to the backend must include the path to the resource.

These available paths are called endpoints. They are described in the backend documentation.

Example:

https://jsonplaceholder.typicode.com/users

This path has two main parts:

Diagram 5. URL structure

https://jsonplaceholder.typicode.com/users
|
|- base URL: https://jsonplaceholder.typicode.com
`- resource: /users

This means: go to this API and give me the users resource.

7. What can endpoints do?

Endpoints let you:

So an endpoint is a specific URL where a certain action or resource is available.

Diagram 6. Endpoint meaning

Endpoint
-> specific URL for a specific resource or action

8. How to check an API response quickly

A simple way to test a public API is:

  1. copy the endpoint
  2. paste it into the browser address bar
  3. open it
  4. the browser sends a request
  5. the server sends JSON back

Diagram 7. Browser test

Paste API URL into browser
-> browser sends request
-> server returns JSON
-> you see data instead of HTML page

This is a very simple way to see whether the API is working.

9. What is Fetch API?

The Fetch API is a browser interface built into the window object.

It lets you send HTTP requests to a server and process the responses. It is based on promises.

Syntax:

fetch(url, options)

Where:

Diagram 8. fetch() idea

fetch(url, options)
-> send HTTP request
-> receive response
-> process result with promises

10. Basic fetch example

fetch("https://jsonplaceholder.typicode.com/users")
  .then(response => {
    // Response handling
  })
  .then(data => {
    // Data handling
  })
  .catch(error => {
    // Error handling
  });

How this works:

Diagram 9. Fetch flow

fetch(...)
-> Promise
-> then(response)
-> then(data)
-> catch(error)

Easy rule:

fetch() returns a Promise

11. What does fetch() return?

Correct answer:

Promise

It does not return the backend data immediately. It returns a promise that will later give you the response.

12. Network tab

The Network tab in developer tools shows all HTTP requests made by the page.

It is very useful for checking:

Diagram 10. Network tab purpose

Page makes request
-> Network tab records it
-> developer can inspect details

13. How to use Network tab

Basic steps:

  1. open developer tools
  2. open the Network tab
  3. choose XHR or Fetch/XHR
  4. run the code with fetch()
  5. click the request in the list
  6. inspect subtabs like Headers, Preview, and Response

Diagram 11. Network tab steps

Open DevTools
-> Open Network
-> Run request
-> Click request
-> Inspect headers / preview / response

This is one of the most important tools for debugging web requests.

14. Response codes

The server response contains a status code.

This code tells the client what happened.

Main groups:

Diagram 12. Status code groups

1XX -> information
2XX -> success
3XX -> redirect
4XX -> client error
5XX -> server error

15. Most common status codes

Important examples:

Diagram 13. Common codes

200 -> success
201 -> created
400 -> bad request
401 -> unauthorized
403 -> forbidden
404 -> not found
500 -> server error

The most important beginner code to remember is:

200 = successful request

16. The Response object

fetch() returns a promise whose fulfilled value is a Response object.

This object contains:

Useful methods include:

Diagram 14. Response object

fetch(...)
-> Promise
-> Response object
   |- status
   |- ok
   |- json()
   |- text()
   `- blob()

17. response.json()

If the server sends JSON data, use:

response.json()

This parses the response body as JSON.

Example

fetch("https://jsonplaceholder.typicode.com/users")
  .then(response => response.json())
  .then(data => {
    console.log(data);
  });

18. Important note: fetch() does not reject for HTTP 404 or 500

This is one of the biggest beginner traps.

fetch() does not automatically reject the promise just because the server returned 404 or 500.

That means you must check the response manually.

Diagram 15. Important fetch() rule

fetch(...)
-> server returns 404 or 500
-> fetch promise may still be fulfilled
-> you must check response.ok manually

catch() usually handles network-level problems. HTTP error codes like 404 still need manual checking.

19. Checking response.ok

The common pattern is:

fetch("https://jsonplaceholder.typicode.com/users")
  .then(response => {
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }
    return response.json();
  })
  .then(data => {
    console.log("Received data:", data);
  })
  .catch(error => {
    console.log("Request error:", error);
  });

Explanation:

Diagram 16. Safe fetch pattern

fetch(...)
-> then(response)
-> check response.ok
   |- true  -> parse JSON
   `- false -> throw Error
-> catch(error)

20. HTTP methods

REST APIs use HTTP methods to define the type of action.

Main methods:

Diagram 17. HTTP methods

GET    -> read
POST   -> create
PUT    -> replace / full update
PATCH  -> partial update
DELETE -> remove

The most important one for this lesson is:

GET = reading data

21. Setting method in fetch()

The method is passed inside the options object.

Example

const options = {
  method: "GET"
};

fetch("https://jsonplaceholder.typicode.com/users", options)
  .then(response => {
    if (!response.ok) {
      throw new Error(response.status);
    }
    return response.json();
  })
  .then(data => {
    console.log(data);
  })
  .catch(error => {
    console.log(error);
  });

Important note: for GET, setting method: "GET" is optional, because GET is the default.

22. HTTP headers

HTTP headers contain service information about the request or response.

A header has:

Examples:

Accept: text/html
Content-Type: application/json

Diagram 18. Header structure

Header
-> Name: Value

Headers help the client and server agree on how data should be handled.

23. Important headers

Common headers include:

Diagram 19. Common headers

Accept         -> expected response type
Content-Type   -> sent/received data type
Authorization  -> auth token / credentials
Cache-Control  -> caching rules
Host           -> target server
User-Agent     -> client information

24. MIME types

Header values often use MIME types.

A MIME type has:

They are separated by /.

Examples:

Diagram 20. MIME type structure

type/subtype

Examples:
text/html
text/css
application/json

This tells the receiver what kind of data is being sent.

25. Passing headers in fetch()

Headers are passed in the headers property of the options object.

Example

fetch("some-url", {
  headers: {
    "Content-Type": "application/json",
    "X-Custom-Header": "custom value",
  }
});

If you want JSON in the response, you may send:

fetch("https://jsonplaceholder.typicode.com/users", {
  headers: {
    Accept: "application/json",
  },
}).then(response => {
  // ...
});

26. CORS

By default, browsers do not freely allow requests to every other domain.

This security policy is called:

CORS = Cross-Origin Resource Sharing

If the request goes to another:

the browser checks whether that request is allowed.

Diagram 21. CORS idea

Page from one origin
-> tries to request another origin
-> browser checks permission

CORS is a browser security rule.

27. What is origin?

An origin means a combination of:

If one of these is different, it is considered cross-origin.

28. The Origin header

When the browser makes a cross-origin request, it automatically adds the Origin header.

Example:

GET /users
Host: my-api.com
Origin: https://my-site.com

The server checks this header to decide whether to allow the request.

Diagram 22. Origin check

Browser sends request
-> includes Origin header
-> server checks it
-> server allows or blocks access

29. Access-Control-Allow-Origin

If the server allows the request, it sends back:

Access-Control-Allow-Origin

Examples:

Access-Control-Allow-Origin: https://my-site.com

or

Access-Control-Allow-Origin: *

Meaning:

Diagram 23. CORS response

Server response
-> Access-Control-Allow-Origin present?
   |- yes -> browser allows access
   `- no  -> browser blocks response

30. Important conclusion about CORS

CORS is configured on the backend, not on the frontend.

If a server does not allow cross-origin requests, frontend code cannot fix that by itself.

You must change backend settings or permissions.

Diagram 24. Who controls CORS?

Frontend wants access
-> browser checks server permission
-> server decides with CORS headers

Easy rule:

CORS problems are usually backend configuration problems

31. Easy memory rules

Server = computer that receives and responds
Backend = server-side program
API = rules for communication
REST API = backend that returns structured data
Endpoint = specific API URL
fetch() = sends HTTP request and returns Promise
response.ok = check HTTP success manually
GET = read data
Headers = service information
CORS = browser cross-origin security rule

32. Quick summary

33. Final conclusion

If you understand these ideas:

server
backend
API
REST API
endpoint
fetch
response
status code
headers
CORS

then you already have a strong foundation for working with HTTP requests in JavaScript.

This topic is very important because modern frontend applications constantly communicate with servers and APIs.

← Back