WisarWisar
Dasturlash kitobi/2-QISM — JavaScript11 daqiqa

2.18-bob: Axios — so'rovlar va interceptors

2-QISM — JavaScript (0 dan chuqurgacha) · 18-mavzu (yakuniy)


1. Kirish va motivatsiya

fetch (2.11, 2.17) — brauzerning native so'rov vositasi, va u yaxshi. Lekin real loyihada ko'pchilik Axios kutubxonasini (npm install axios — 0.7) afzal ko'radi, chunki u fetchning bir nechta noqulayligini hal qiladi va kuchli interceptor tizimi beradi.

Axios — Promise asosidagi HTTP klient (brauzer + Node) (axios-http.com). U: avtomatik JSON, qulay xato boshqaruvi, so'rov/javobni interceptor bilan global o'zgartirish (har so'rovga token qo'shish!), timeout, so'rovni bekor qilish — hammasini sodda qiladi.

O'xshatish: fetch — qo'l asbobi (bolg'a). Axios — elektr asbobi (perforator): bir xil ish, lekin ko'p qulaylik qo'shilgan. Kichik ishda fetch yetadi; katta loyihada Axios tezroq va xavfsizroq.

Bu — 2-QISMning so'nggi bobi! Axios — React (11, 12), backend so'rovlari (5) va auth 5.15-bob da keng ishlatiladi. Interceptor — token qo'shish va global xato uchun professional naqsh.


2. Nazariya — chuqur tushuntirish

2.1. fetch vs Axios

fetch (native) Axios (kutubxona)
O'rnatish yo'q (built-in) npm install axios (0.7)
JSON qo'lda res.json() avtomatik (res.data)
Xato (4xx/5xx) res.ok qo'lda (0.4) avtomatik throw (catch)
Timeout AbortController (2.17) sodda timeout opsiyasi
Interceptor yo'q bor (kuchli — 2.5)
Node yangi Node'da bor ishlaydi

Qaysini? Kichik loyiha/bitta so'rov — fetch (qo'shimcha paketsiz). Katta loyiha, ko'p so'rov, auth — Axios (interceptor, qulaylik). Ikkalasini ham bilish kerak.

2.2. Asosiy so'rovlar

js
import axios from "axios";   // (2.14: ESM)

// GET — avtomatik JSON (res.data)
const res = await axios.get("https://api.example.com/users");
console.log(res.data);        //  avtomatik parse (fetch'da res.json() kerak edi)

// POST — body to'g'ridan-to'g'ri (stringify SHART emas!)
await axios.post("/api/users", { ism: "Ali", yosh: 19 });
// (Content-Type: application/json AVTOMATIK qo'yiladi — 0.4)

// PUT, PATCH, DELETE (0.4)
await axios.put("/api/users/1", data);
await axios.patch("/api/users/1", { yosh: 20 });
await axios.delete("/api/users/1");

fetch'dan farq: (1) res.data — avtomatik JSON 2.8-bob; (2) body obyektni JSON.stringifysiz; (3) Content-Type avtomatik. Sodda.

2.3. Response obyekti

js
const res = await axios.get("/api/user/1");
res.data;        // javob bodysi (ASOSIY — avtomatik parse)
res.status;      // 200 (0.4)
res.statusText;  // "OK"
res.headers;     // javob headerlari (0.4)
res.config;      // so'rov sozlamalari

Config (so'rov) obyekti — har metodning oxirgi argumenti; so'rovni sozlash (axios-http.com):

js
await axios.get("/users", {
  params: { page: 2 },      // URL query  ?page=2 (0.4, 2.7)
  headers: { "X-Token": "abc" },  // qo'shimcha headerlar (0.4)
  timeout: 5000,            // 5 sek; oshsa — bekor (2.6)
  signal: controller.signal,  // bekor qilish (AbortController — 2.17, 2.7)
});

// POST/PUT/PATCH'da body 2-argument, config 3-argument
await axios.post("/users", { ism: "Ali" }, { headers: { /* ... */ } });

Eslatma: get/deleteda config — 2-argument; post/put/patchda body 2-, config 3-argument. Adashtirmang.

2.4. Xato boshqaruvi (2.12)

Axios 4xx/5xx 0.4-bob da avtomatik throw qiladi (fetch'da qo'lda edi):

js
try {
  const res = await axios.get("/api/user/999");
  return res.data;
} catch (error) {
  if (error.response) {
    // Server javob berdi, lekin xato status (4xx/5xx — 0.4)
    console.log(error.response.status);   // 404
    console.log(error.response.data);     // server xato xabari
  } else if (error.request) {
    // So'rov ketdi, lekin javob yo'q (tarmoq/timeout)
    console.log("Javob kelmadi");
  } else {
    // So'rovni sozlashda xato
    console.log(error.message);
  }
}

2.5. Interceptors — eng kuchli imkoniyat

Interceptor — har so'rov yuborilishdan oldin yoki har javob kelgandan keyin ishlaydigan funksiya (Express middleware'ga o'xshash — 5.6, axios-http.com):

js
// REQUEST interceptor — har so'rovdan OLDIN (masalan token qo'shish — 5.15)
axios.interceptors.request.use((config) => {
  const token = localStorage.getItem("token");   // (2.17)
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;   // har so'rovga token! (0.4)
  }
  return config;   //  config'ni QAYTARISH shart
});

// RESPONSE interceptor — har javobdan KEYIN (global xato — 5.15)
axios.interceptors.response.use(
  (response) => response,            // muvaffaqiyat — o'tkaz
  (error) => {
    if (error.response?.status === 401) {   // ruxsatsiz (0.4)
      localStorage.removeItem("token");
      window.location.href = "/login";       // login'ga yo'naltir
    }
    return Promise.reject(error);   // xatoni qayta tashla (2.11)
  }
);

Nega interceptor kuchli: (1) token'ni bir joyda har so'rovga qo'shish (har funksiyada takrorlamasdan); (2) global xato (401 logout) bir joyda; (3) logging, loading indikator. Bu — auth 5.15-bob va katta loyihaning standart naqshi.

2.6. Axios instance — sozlangan klient

Takrorlanuvchi sozlamalarni (base URL, header, timeout) bir marta belgilash:

js
// api.js — sozlangan instance (2.14: modul)
const api = axios.create({
  baseURL: "https://api.example.com",   // har so'rovga qo'shiladi
  timeout: 10000,                       // 10 sek (2.17: AbortController g'oyasi)
  headers: { "Content-Type": "application/json" },
});

// Interceptor instance'ga (2.5)
api.interceptors.request.use(config => { /* token */ return config; });

export default api;   // (2.14)

// Ishlatish (boshqa faylda)
import api from "./api.js";
const res = await api.get("/users");   // baseURL avtomatik  /users to'liq URL

Best practice: bitta sozlangan api instance yaratib, butun loyihada ishlatish. Base URL, token, timeout — bir joyda. (React loyihalarida standart — 11, 12.)

2.7. Qo'shimcha imkoniyatlar

js
// Query parametrlar (0.4: URL query)
api.get("/users", { params: { page: 2, limit: 10 } });   // ?page=2&limit=10

// Parallel so'rovlar (2.11: Promise.all)
const [users, posts] = await Promise.all([api.get("/users"), api.get("/posts")]);

// So'rovni bekor qilish (AbortController — 2.17)
const controller = new AbortController();
api.get("/data", { signal: controller.signal });
controller.abort();

3. Sintaksis — tez ma'lumotnoma

js
import axios from "axios";

axios.get(url, { params })       // res.data, res.status
axios.post(url, data)            // body avtomatik JSON
axios.put/patch/delete(url, data)

// Instance (2.6)
const api = axios.create({ baseURL, timeout, headers });

// Interceptors (2.5)
api.interceptors.request.use(config => { ...; return config; });
api.interceptors.response.use(res => res, err => Promise.reject(err));

// Xato (2.4)
catch (err) { err.response?.status; err.response?.data; }

4. Batafsil kod namunalari

Misol 1 — Asosiy CRUD (2.2)

js
import axios from "axios";
const URL = "https://jsonplaceholder.typicode.com";

// GET
const userlar = (await axios.get(`${URL}/users`)).data;   // avtomatik JSON (2.2)

// POST — body to'g'ridan-to'g'ri (2.2)
const yangi = (await axios.post(`${URL}/posts`, {
  title: "Salom", body: "Matn", userId: 1,
})).data;

// DELETE
await axios.delete(`${URL}/posts/1`);

Misol 2 — Sozlangan instance + token interceptor (2.5, 2.6)

js
// api.js
import axios from "axios";

const api = axios.create({
  baseURL: "https://api.example.com",
  timeout: 10000,
});

// Har so'rovga token (auth — 5.15)
api.interceptors.request.use((config) => {
  const token = localStorage.getItem("token");   // (2.17)
  if (token) config.headers.Authorization = `Bearer ${token}`;
  return config;
});

// 401  logout (global — 2.5)
api.interceptors.response.use(
  (res) => res,
  (err) => {
    if (err.response?.status === 401) {
      localStorage.removeItem("token");
      window.location.href = "/login";
    }
    return Promise.reject(err);
  }
);

export default api;   // (2.14)

Misol 3 — Xato boshqaruvi (2.4, 2.12)

js
import api from "./api.js";

async function userOl(id) {
  try {
    const res = await api.get(`/users/${id}`);
    return res.data;
  } catch (err) {
    if (err.response) {
      // server javob berdi (4xx/5xx — 0.4)
      if (err.response.status === 404) return null;   // topilmadi — kutilgan
      throw new Error(`Server xatosi: ${err.response.status}`);   // (2.12)
    } else if (err.code === "ECONNABORTED") {
      throw new Error("Vaqt tugadi (timeout)");        // (2.6)
    } else {
      throw new Error("Tarmoq xatosi");
    }
  }
}

Misol 4 — Loading va parallel (2.7, 2.11)

js
async function dashboardYukla() {
  // Loading interceptor (har so'rovda indikator — soddalashtirilgan)
  let yuklanmoqda = true;

  try {
    // Parallel — tez (2.11, 2.7)
    const [users, posts, stats] = await Promise.all([
      api.get("/users"),
      api.get("/posts", { params: { limit: 5 } }),   // query (2.7)
      api.get("/stats"),
    ]);
    return {
      users: users.data,
      posts: posts.data,
      stats: stats.data,
    };
  } finally {
    yuklanmoqda = false;   // har holda (2.12)
  }
}

5. To'g'ri va noto'g'ri holatlar

1) Token'ni har so'rovga qo'lda qo'shish

js
//  har funksiyada takror (xato manbai)
axios.get("/a", { headers: { Authorization: `Bearer ${token}` } });
axios.get("/b", { headers: { Authorization: `Bearer ${token}` } });

//  interceptor — bir joyda (2.5)
api.interceptors.request.use(c => { c.headers.Authorization = `Bearer ${token}`; return c; });

2) Interceptor'da config/error qaytarmaslik

js
//  config qaytarilmadi — so'rov "osib qoladi"
api.interceptors.request.use((config) => { config.headers.X = "1"; });

//  doim qaytar (2.5)
api.interceptors.request.use((config) => { config.headers.X = "1"; return config; });

3) Xatoni err.responsesiz o'qish

js
//  tarmoq xatosida err.response yo'q  xato (2.4)
catch (err) { console.log(err.response.status); }

//  tekshir (2.1)
catch (err) { console.log(err.response?.status ?? "Tarmoq xatosi"); }

4) Har joyda yangi axios sozlamasi

js
//  takror sozlama
axios.get("https://api.example.com/users", { timeout: 10000, headers: {...} });

//  bitta instance (2.6)
api.get("/users");

6. Keng tarqalgan xatolar va yechimlari

Xato 1 — Cannot read properties of undefined (reading 'status')

Sababi: err.response yo'q (tarmoq/timeout — javob kelmadi — 2.4). Yechimi: err.response?.status 2.1-bob; err.request/err.codeni ham tekshiring.

Xato 2 — Token qo'shilmaydi

Sababi: interceptor'da return config yo'q, yoki token localStorage'da yo'q (2.5, 2.17). Yechimi: configni qaytaring; token borligini tekshiring.

Xato 3 — CORS xatosi

Sababi: boshqa domen ruxsat bermadi (0.4, 5.20). Yechimi: server CORS sozlasin (Axios/fetch farqi yo'q — bu server muammosi — 0.4).

Xato 4 — Network Error (lokalda)

Sababi: server ishlamayapti (0.4: ECONNREFUSED), noto'g'ri baseURL, yoki HTTPS/HTTP. Yechimi: server ishlayotganini, URL/portni tekshiring 0.4-bob.

Xato 5 — Interceptor cheksiz loop (401 refresh)

Sababi: 401'da token refresh so'rovi yana 401 cheksiz. Yechimi: refresh so'rovini interceptor'dan istisno qiling; _retry bayroqi (5.16: refresh token).


7. Integratsiya — bu mavzu stack'ning qayerida uchraydi

  • fetch/async (2.11, 2.17): Axios — fetch'ga muqobil; bir xil Promise asosi.
  • Auth (5.15, 5.16): token interceptor; 401 refresh/logout.
  • React (11, 12): komponentlarda api instance; TanStack Query/RTK Query — Axios ustida.
  • Error handling 2.12-bob: err.response bilan boshqarish.
  • Modullar 2.14-bob: api.js — sozlangan instance, import.
  • Backend (5): server ham Axios bilan boshqa API'larga so'rov (5.18: SMS).
  • localStorage 2.17-bob: token saqlash + interceptor.

8. Eng yaxshi amaliyotlar (best practices)

  • Bitta sozlangan api instance (baseURL, timeout) — butun loyihada 2.6-bob.
  • Token'ni request interceptor'da qo'shing — bir joyda, takrorsiz 2.5-bob.
  • Global xato (401) — response interceptor'da (logout/refresh — 2.5).
  • Interceptor'da doim return config/Promise.reject (5-bo'lim).
  • err.response?. bilan xatoni xavfsiz o'qi (2.4, 2.1).
  • Parallel so'rovlar — Promise.all (2.11, 2.7).
  • Maxfiy ma'lumot/token — ehtiyot (XSS — 14; httpOnly cookie afzal — 5.15).
  • Kichik loyihada fetch yetsa — Axios shart emas (qo'shimcha paket — 2.1).

9. Amaliy loyiha: "API Klient Qatlami (Service Layer)"

Axios'ni professional tarzda tashkil qiluvchi loyiha — 2-QISMni yakunlovchi.

Maqsad

Sozlangan instance, interceptor va xato boshqaruvini birlashtirib, qayta ishlatiladigan, xavfsiz API klient qatlami qurish.

Talablar (requirements)

  1. api.js instance: baseURL, timeout, default header (Misol 2, 2.6).
  2. Request interceptor: localStorage'dan token olib, har so'rovga Authorization qo'shing (Misol 2, 2.5).
  3. Response interceptor: 401 token o'chiring + login'ga yo'naltiring; boshqa xatoni qayta tashlang 2.5-bob.
  4. Service modullari 2.14-bob: userService.js (getAll, getById, create, update, delete), postService.js — har biri api instance'ni ishlatadi.
  5. Xato boshqaruvi: har service funksiyasida err.responsega qarab aniq xabar (404, timeout, tarmoq — Misol 3, 2.12).
  6. Parallel: dashboard ma'lumotini Promise.all bilan oling (Misol 4, 2.11).
  7. Query param: sahifalash (?page=&limit=) bilan ma'lumot oling 2.7-bob.
  8. Loading holati: so'rov davomida indikator (oddiy bayroq yoki interceptor bilan — bonus).
  9. Ochiq API ishlating (jsonplaceholder.typicode.com); token uchun soxta qiymat.

Maslahatlar (hint)

  • axios.create({ baseURL: "https://jsonplaceholder.typicode.com" }) 2.6-bob.
  • Interceptor'da doim return config (5-bo'lim).
  • Service: export const userService = { getAll: () => api.get("/users").then(r => r.data), ... } 2.14-bob.
  • Xato: err.response?.status (2.1, 2.4); 404 null, boshqa throw.
  • Parallel: Promise.all([userService.getAll(), postService.getAll()]) 2.11-bob.
  • Query: api.get("/posts", { params: { _page: 1, _limit: 10 } }) 2.7-bob.

"Tayyor" mezonlari (acceptance criteria)

  • Sozlangan api instance (baseURL/timeout) ishlaydi.
  • Request interceptor token qo'shadi (return config bor).
  • Response interceptor 401'ni boshqaradi.
  • Kamida 2 service moduli (CRUD funksiyalari bilan).
  • Xato boshqaruvi (404/timeout/tarmoq) ajratilgan.
  • Parallel so'rov (Promise.all) ishlatilgan.
  • Query param bilan sahifalash.
  • err.response?. bilan xavfsiz o'qish.

Yechim kodi ataylab berilmagan — bu loyihani o'zingiz yozib ko'ring.


10. Xulosa — 2-QISM yakunlandi!

Bu bobda professional HTTP klientni — Axiosni o'rgandik:

  • Axios — Promise asosidagi HTTP klient; fetchdan: avtomatik JSON (res.data), avtomatik xato throw (4xx/5xx), interceptor, qulay sozlama.
  • So'rovlar: axios.get/post/put/delete; body avtomatik JSON; res.data.
  • Xato: err.response (server xato), err.request (javob yo'q) — ajratib boshqaring 2.12-bob.
  • Interceptor (eng kuchli): request (token qo'shish — 5.15), response (401 logout) — bir joyda, takrorsiz.
  • Instance (axios.create) — baseURL/timeout/token bir marta; butun loyihada.

2-QISM (JavaScript) — to'liq yakunlandi! (18 bob)

Siz endi JavaScript'ni chuqur bilasiz: turlar, funksiya, closure, this/prototype, OOP, asinxron (Promise/async-await), error handling, DOM, modullar, FP, browser API, Axios. Bu — butun kitobning eng katta va eng muhim qismi.

Keyingi bob — 3.1-bob: Big-O notatsiyasi. 3-QISM (Algoritm va ma'lumotlar tuzilmasi) boshlanadi. JS'ni bildik; endi kodni samarali yozishni — algoritm tezligini (Big-O) o'lchashni o'rganamiz. Bu — 0.1 (xotira/CPU) va 2.7 (Array) ustiga quriladi; intervyularning markaziy mavzusi.


Foydalanilgan rasmiy/ishonchli manbalar

  • axios-http.com — Axios docs, interceptors, instance, config
  • axios-http.com — error handling, request/response interceptors
  • MDN Web Docs — Fetch API (Axios bilan taqqoslash uchun)

Izohlar (0)

Izoh yozish uchun kiring.

  • Hozircha izoh yo'q. Birinchi bo'ling!
2.18-bob: Axios — so'rovlar va interceptors — Wisar