Introduction to Javascript, data types, varibles and if-else conditions
JSON
- JSON stands for JavaScript Object Notation. It is used to store and exchange data.
Accessing Data from JSON
- If you have a JavaScript object, you can access data using:
const user = {
name: 'Alice',
age: 25,
}
console.log(user.name) // Alice
console.log(user['age']) // 25
JSON.parse() Method
JSON.parse()is used to convert a JSON string into a JavaScript object.
const jsonData = '{"name":"Bob","age":30}'
const obj = JSON.parse(jsonData) // converts to JavaScript object
console.log(obj) // {name: 'Bob', age: 30}
console.log(obj.name) // Bob
console.log(obj.age) // 30
JSON.stringify() Method
JSON.stringify()is used to convert a JavaScript object into a JSON string.
const obj = {
name: "Charlie",
age: 28
};
const jsonString = JSON.stringify(obj);
console.log(jsonString); // {"name":"Charlie","age":28}
fetch
- fetch data from server.
Get Request
async function getPost() {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/posts/1');
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Error:', error);
}
}
getPost();
// {userId: 1, id: 1, title: 'sunt aut facere repellat provident occaecati excepturi optio reprehenderit', body: 'quia et suscipit\nsuscipit recusandae consequuntur …strum rerum est autem sunt rem eveniet architecto'}
post
- send data to the server.
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
title: 'Hello World',
body: 'This is a test post',
userId: 1
})
})
.then(response => response.json())
.then(data => console.log('POST Success:', data))
.catch(error => console.error('Error:', error));
// POST Success: {title: 'Hello World', body: 'This is a test post', userId: 1, id: 101}
put
- Update Data Fully
fetch('https://jsonplaceholder.typicode.com/posts/1', {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
id: 1,
title: 'Updated Title',
body: 'Updated body content',
userId: 1
})
})
.then(response => response.json())
.then(data => console.log('PUT Success:', data))
.catch(error => console.error('Error:', error));
// PUT Success: {id: 1, title: 'Updated Title', body: 'Updated body content', userId: 1}
patch
- Update Data Partially.
fetch('https://jsonplaceholder.typicode.com/posts/1', {
method: 'PATCH',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
title: 'Only Title Updated'
})
})
.then(response => response.json())
.then(data => console.log('PATCH Success:', data))
.catch(error => console.error('Error:', error));
// PATCH Success: {userId: 1, id: 1, title: 'Only Title Updated', body: 'quia et suscipit\nsuscipit recusandae consequuntur …strum rerum est autem sunt rem eveniet architecto'}
delete
- Remove Data
fetch('https://jsonplaceholder.typicode.com/posts/1', {
method: 'DELETE'
})
.then(response => {
if (response.ok) {
console.log('DELETE Success');
} else {
console.error('Delete Failed');
}
})
.catch(error => console.error('Error:', error));
// DELETE Success
summary
| Method | Purpose | Requires Body? | Typical Use |
|---|---|---|---|
| GET | Fetch data | ❌ No | Read-only data |
| POST | Create new data | ✅ Yes | Register, Create |
| PUT | Replace existing | ✅ Yes | Full update |
| PATCH | Update part of data | ✅ Yes | Update specific fields |
| DELETE | Remove data | ❌ Optional | Delete an item |
HTTP Status Codes
| Code | Type | Status | Description |
|---|---|---|---|
| 100 | 1xx Info | Continue | Request received, client can continue sending the rest. |
| 101 | 1xx Info | Switching Protocols | Protocol switch request accepted (e.g., to WebSocket). |
| 200 | 2xx Success | OK | Standard response for a successful request. |
| 201 | 2xx Success | Created | Request successful, and a new resource was created. |
| 202 | 2xx Success | Accepted | Request accepted, processing is not yet complete. |
| 204 | 2xx Success | No Content | Success, but no data returned. |
| 206 | 2xx Success | Partial Content | Partial data (useful for range requests). |
| 301 | 3xx Redirect | Moved Permanently | Resource has been permanently moved to a new URI. |
| 302 | 3xx Redirect | Found | Temporarily redirected to a different URI. |
| 304 | 3xx Redirect | Not Modified | Resource has not changed (use cached version). |
| 307 | 3xx Redirect | Temporary Redirect | Redirect with same method (e.g., POST remains POST). |
| 308 | 3xx Redirect | Permanent Redirect | Redirect with same method permanently. |
| 400 | 4xx Client | Bad Request | Client sent invalid or incomplete request. |
| 401 | 4xx Client | Unauthorized | Request lacks valid authentication credentials. |
| 403 | 4xx Client | Forbidden | Authenticated but not allowed to access the resource. |
| 404 | 4xx Client | Not Found | Resource or endpoint doesn’t exist. |
| 405 | 4xx Client | Method Not Allowed | HTTP method (e.g., PUT/DELETE) not supported for this resource. |
| 408 | 4xx Client | Request Timeout | Server timed out waiting for the request. |
| 409 | 4xx Client | Conflict | Request could not be completed due to conflict (e.g., duplicate data). |
| 422 | 4xx Client | Unprocessable Entity | Request is well-formed but contains semantic errors (e.g., validation fail). |
| 429 | 4xx Client | Too Many Requests | Client has sent too many requests in a given time (rate limiting). |
| 500 | 5xx Server | Internal Server Error | General server error; something went wrong on the server side. |
| 501 | 5xx Server | Not Implemented | Server does not recognize or support the request method. |
| 502 | 5xx Server | Bad Gateway | Server received an invalid response from the upstream server. |
| 503 | 5xx Server | Service Unavailable | Server is overloaded or down for maintenance. |
| 504 | 5xx Server | Gateway Timeout | Upstream server failed to respond in time. |
What is a Query String?
- A query string is the part of a URL that passes data to the server.
It starts with
?and has key-value pairs separated by&.
How to Create a Query String ?
Manually
const url = "https://example.com/search?name=John&age=25";
Using URLSearchParams
const params = new URLSearchParams({
name: 'John',
age: 25,
city: 'Delhi',
})
const url = `https://example.com/profile?${params.toString()}`
console.log(url) // https://example.com/profile?name=John&age=25&city=Delhi
How to Read Query Strings in JavaScript ?
// const url = new URL(window.location.href)
const url = new URL('https://example.com/profile?name=John&age=25&city=Delhi')
const params = new URLSearchParams(url.search)
console.log(params)
console.log(params.get("name")); // Output: "John"
console.log(params.get("age")); // Output: "25"
Axios
- Axios is a promise-based HTTP client for the browser and Node.js.
It’s used to send
GET,POST,PUT,DELETE, etc., requests to APIs. npm install axios- CDN -
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Axios Test</title>
</head>
<body style="background-color: rgb(53, 52, 52); color: white;">
<h1>Axios Test</h1>
<!-- Load Axios from CDN -->
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<!-- Then load your own script -->
<script src="script.js"></script>
</body>
</html>
GET Request
axios
.get('https://jsonplaceholder.typicode.com/users/1')
.then((response) => {
console.log(response.data) // Output the data
})
.catch((error) => {
console.error(error)
})
// {id: 1, name: 'Leanne Graham', username: 'Bret', email: 'Sincere@april.biz', address: {…}, …}
POST Request
axios
.post('https://jsonplaceholder.typicode.com/posts', {
title: 'Hello',
body: 'This is a post',
userId: 1,
})
.then((response) => {
console.log(response.data)
})
.catch((error) => {
console.error(error)
})
// {title: 'Hello', body: 'This is a post', userId: 1, id: 101}
PUT Request
axios.put('https://jsonplaceholder.typicode.com/posts/1', {
title: 'Updated title',
body: 'Updated body',
userId: 1
})
.then(response => console.log(response.data))
.catch(error => console.error(error));
// {title: 'Updated title', body: 'Updated body', userId: 1, id: 1}
DELETE Request
axios.delete('https://jsonplaceholder.typicode.com/posts/1')
.then(response => console.log('Deleted'))
.catch(error => console.error(error));
// Deleted
PATCH Request
axios.patch('https://jsonplaceholder.typicode.com/posts/1', {
title: 'Updated Title Only'
})
.then(response => {
console.log('Patch Response:', response.data);
})
.catch(error => {
console.error('Error:', error);
});
// Patch Response: {userId: 1, id: 1, title: 'Updated Title Only', body: 'quia et suscipit\nsuscipit recusandae consequuntur …strum rerum est autem sunt rem eveniet architecto'}
Sending Headers
axios
.get('https://jsonplaceholder.typicode.com/posts/1', {
headers: {
Authorization: 'Bearer YOUR_TOKEN',
'Content-Type': 'application/json',
},
})
.then((res) => console.log(res.data))
.catch((err) => console.error(err))
Handling Query Parameters
axios.get('https://jsonplaceholder.typicode.com/posts/1', {
params: {
query: 'books',
page: 2
}
})
.then(res => console.log(res.data))
.catch(err => console.error(err));
What is the use of Content-Type header?
- The Content-Type header tells the server what kind of data you are sending in the body of the HTTP request.
headers: {
'Content-Type': 'application/json'
}
- The request body contains JSON data.
- So the server knows to parse the body as JSON.
Why is this important?
- If the server expects JSON but you don’t set Content-Type: application/json, it might fail to parse the request body correctly.
- For example, if you send data as JSON without this header, the server may think it’s plain text or some other format and reject or misinterpret it.
Difference b/w fetch and Axios
| Feature | fetch | axios |
|---|---|---|
| What is it? | Native browser API for making HTTP requests | Third-party library built on top of XMLHttpRequest (XHR) |
| Installation | No installation needed (built-in in modern browsers) | Requires installation (npm install axios) |
| Browser support | Supported in modern browsers, older browsers need polyfill | Works on most browsers including older ones |
| Syntax | Uses native Promises, simple but requires manual JSON parsing | Uses Promises, automatically parses JSON responses |
| Response parsing | You manually parse with .json(), .text(), etc. | Response data is automatically parsed (response.data) |
| Error handling | Only rejects on network failure, not on HTTP errors | Rejects on HTTP error status codes (like 404, 500) |
| Request cancellation | Supported via AbortController | Supports cancellation with CancelToken |
| Interceptors | Not supported | Supports request and response interceptors (middleware) |
| Request timeout | No built-in support | Built-in timeout support |
| Automatic transforms | None | Supports request/response transformation |
| Uploading/downloading progress | Not supported directly | Supports progress tracking |
| JSON handling | You manually call .json() on response | Automatically serializes JS objects to JSON and parses JSON |
| Convenience | Basic, flexible but needs more code for common tasks | More features out of the box, easier for complex requests |