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:
- what a server is
- what backend means
- what an API is
- what a REST API is
- what a resource path or endpoint is
- what
fetch()does - how to inspect requests in the Network tab
- what response codes mean
- how to check
response.ok - what HTTP methods and headers are
- 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:
- receives incoming HTTP requests
- processes data
- performs the needed actions
- sends a response back to the client, often in JSON format
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:
- what you can ask a program to do
- what you will get back
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:
- how resources are named
- how resources are addressed
- how the client interacts with them through HTTP requests
A REST API often acts as an intermediary between:
- a web application
- and a database
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:
- users
- posts
- comments
- products
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:
https://jsonplaceholder.typicode.comis the base URL/usersis the resource path
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:
- get data
- send new data
- update data
- delete data
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:
- copy the endpoint
- paste it into the browser address bar
- open it
- the browser sends a request
- 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:
urlis the required path to the resourceoptionsis an optional settings object
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:
fetch()sends a request and returns a promise- the first
then()runs when the response arrives - the next
then()processes the data catch()handles errors
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:
- request URL
- request method
- headers
- response data
- status codes
- errors
Diagram 10. Network tab purpose
Page makes request
-> Network tab records it
-> developer can inspect details
13. How to use Network tab
Basic steps:
- open developer tools
- open the Network tab
- choose XHR or Fetch/XHR
- run the code with
fetch() - click the request in the list
- 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:
1XXmeans informational2XXmeans success3XXmeans redirects4XXmeans client errors5XXmeans server errors
Diagram 12. Status code groups
1XX -> information
2XX -> success
3XX -> redirect
4XX -> client error
5XX -> server error
15. Most common status codes
Important examples:
200 OKmeans successful request201 Createdmeans resource successfully created400 Bad Requestmeans request is invalid401 Unauthorizedmeans authorization required403 Forbiddenmeans access denied404 Not Foundmeans resource not found500 Internal Server Errormeans server-side failure
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:
- status information
- response metadata
- methods for reading the body
Useful methods include:
response.json()response.text()response.blob()
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:
response.okistruefor successful responses- if it is
false, throw an error - then
catch()can handle it
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:
GETreads dataPOSTcreates dataPUTupdates fully or createsPATCHupdates partiallyDELETEdeletes data
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:
- a name
- a value
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:
Acceptmeans what format the client can acceptContent-Typemeans what format the body usesAuthorizationcontains authentication dataCache-Controlcontains caching rulesHostcontains the server domainUser-Agentcontains browser or client info
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:
- type
- subtype
They are separated by /.
Examples:
text/htmltext/cssapplication/json
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:
- domain
- port
- protocol
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:
- protocol
- domain
- port
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:
- specific site allowed
- or everyone allowed
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
- A server receives and processes network requests.
- The backend is the program running on the server.
- An API is a set of rules for interacting with a program.
- A REST API usually returns JSON data instead of HTML.
- An endpoint is a specific URL for a resource or function.
fetch()sends HTTP requests and returns a promise.- The Network tab helps inspect requests, responses, headers, and status codes.
- Status code
200means success. fetch()does not automatically reject for404or500, so you should checkresponse.ok.GETis used to read data.- Headers describe request and response details.
- CORS is a browser security policy for cross-origin requests.
- CORS is configured on the backend.
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.