Server Communication Lecture Notes
Controller ka Role in Model, View, Controller (MVC):
Controller ka kaam hai model ko fetch karna view ke liye.
Browser web server se baat karta hai aur wahi model ko request karta hai.
AJAX (Asynchronous JavaScript and XML) use hota hai JavaScript ke through HTTP
request karne ke liye bina DOM elements add kare.
Aajkal JSON zyada use hota hai instead of XML.
XMLHttpRequest: HTTP Requests bhejna:
Example code:
```
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText);
}
};
xhr.open("GET", "https://example.com/api");
xhr.send();
```
States ka matlab:
0: UNSENT (Request abhi shuru nahi hua).
1: OPENED (send() call hua).
2: HEADERS_RECEIVED (Headers available hain).
3: LOADING (Data download ho raha hai).
4: DONE (Request complete hai).
REST API:
REST ka full form hai Representational State Transfer.
CRUD operations (Create, Read, Update, Delete) ko HTTP methods ke zariye map
karta hai:
GET: Data retrieve karna.
POST: Naya data create karna.
PUT: Existing data update karna.
DELETE: Data delete karna.
Example:
GET /photos/ (Photos ki collection).
GET /photos/12345 (Specific photo resource).
React aur REST APIs:
React frameworks XMLHttpRequest ko zyada use nahi karte; instead, Axios ya Fetch
popular hain.
Example code:
```
// Axios se GET request
axios.get('https://example.com/api/photos')
.then(response => console.log(response.data))
.catch(error => console.error(error));
// Fetch API se GET request
fetch('https://example.com/api/photos')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
```
Promises aur Async/Await:
Promises: Callbacks ke comparison mein zyada readable aur structured hote hain.
Example code:
```
fetch('https://example.com/api/photos')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
```
Async/Await: Code ko synchronous flow deta hai.
Example code:
```
async function fetchPhotos() {
try {
let response = await fetch('https://example.com/api/photos');
let data = await response.json();
console.log(data);
} catch (error) {
console.error(error);
}
}
fetchPhotos();
```
WebSockets:
HTML5 WebSockets: Full-duplex communication (Dono taraf ek waqt par data send aur
receive karna).
Example code:
```
let socket = new WebSocket("ws://example.com/socketserver");
socket.onopen = () => socket.send(JSON.stringify({ type: "subscribe", channel:
"updates" }));
socket.onmessage = (event) => console.log(JSON.parse(event.data));
```
GraphQL:
Facebook ka protocol jo REST ke mukable ek flexible option hai.
Schema: Server resources ke properties define karta hai.
Ek query se multiple resources fetch kiye ja sakte hain.