Перейти к содержанию
  • Лента
  • Категории
  • Последние
  • Метки
  • Популярные
  • Пользователи
  • Группы
Свернуть
exlends
Категории
  1. Главная
  2. Категории
  3. Programming languages
  4. JavaScript
  5. How to Make HTTP GET/POST Requests in JavaScript (for Web and Mobile)

How to Make HTTP GET/POST Requests in JavaScript (for Web and Mobile)

Запланировано Прикреплена Закрыта Перенесена JavaScript
javascripthttpapi
1 Сообщения 1 Постеры 47 Просмотры
  • Сначала старые
  • Сначала новые
  • По количеству голосов
Ответить
  • Ответить, создав новую тему
Авторизуйтесь, чтобы ответить
Эта тема была удалена. Только пользователи с правом управления темами могут её видеть.
  • hannadevH Не в сети
    hannadevH Не в сети
    hannadev
    написал в отредактировано hannadev
    #1

    Let’s be real: if your app doesn’t talk to a server, it’s basically a fancy notepad. Whether you’re fetching user data, submitting a form, or syncing preferences across devices—you’ll need to send HTTP requests. And in the JavaScript world, that usually means GET and POST.

    Good news? Making these requests is easier than ever—thanks to modern APIs like fetch() and battle-tested libraries like Axios. Even better? The same code often works seamlessly on both web browsers and mobile apps (especially if you’re using React Native or hybrid frameworks).

    So grab your favorite drink, and let’s break this down—no jargon overload, just clear, practical steps.


    🧭 Why This Matters

    Before we dive into syntax, let’s zoom out:

    • GET = “Hey server, give me some data.” (e.g., load a user profile)
    • POST = “Hey server, here’s some data—save it!” (e.g., submit a login form)

    These are the bread and butter of client-server communication. And JavaScript? It’s the universal translator.


    ✅ Option 1: The Built-in Hero — fetch()

    Modern browsers (and React Native!) support the Fetch API natively. No extra libraries. No fuss.

    🔹 Making a GET Request

    fetch('https://api.example.com/users')
      .then(response => {
        if (!response.ok) {
          throw new Error('Network response was not ok');
        }
        return response.json(); // Parse JSON response
      })
      .then(data => {
        console.log('Success:', data);
      })
      .catch(error => {
        console.error('Error:', error);
      });
    

    💡 Pro tip: Always check response.ok! A 404 or 500 still returns a “response”—but it’s not successful.

    🔹 Making a POST Request

    fetch('https://api.example.com/login', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        email: 'you@example.com',
        password: 'supersecret'
      })
    })
    .then(response => response.json())
    .then(data => console.log('Login success:', data))
    .catch(error => console.error('Login failed:', error));
    

    Key things to note:

    • method: 'POST' tells the server what you’re doing.
    • headers specify the data format (usually JSON).
    • body must be a string—so we use JSON.stringify().

    🚀 Option 2: The Powerhouse — Axios

    If you want more features out of the box (automatic JSON parsing, request/response interceptors, better error handling), Axios is your friend.

    Install it:

    # Web (via npm)
    npm install axios
    
    # React Native
    npm install axios
    # (or use Expo’s built-in fetch—both work!)
    

    🔹 GET with Axios

    import axios from 'axios';
    
    axios.get('https://api.example.com/users')
      .then(response => {
        console.log('Users:', response.data);
      })
      .catch(error => {
        console.error('Error fetching users:', error);
      });
    

    🔹 POST with Axios

    axios.post('https://api.example.com/login', {
      email: 'you@example.com',
      password: 'supersecret'
    })
    .then(response => {
      console.log('Login response:', response.data);
    })
    .catch(error => {
      console.error('Login error:', error.response?.data || error.message);
    });
    

    🌟 Bonus: Axios automatically transforms JSON requests/responses—no JSON.stringify() or .json() needed!


    📱 Does This Work on Mobile?

    Yes—with caveats.

    Platform fetch() Axios
    Web (Chrome, Firefox, etc.) ✅ Full support ✅
    React Native ✅ Built-in ✅ (via npm)
    Capacitor / Cordova ✅ ✅
    Expo ✅ ✅

    ⚠️ One gotcha: CORS doesn’t apply in mobile apps (since there’s no browser sandbox), but you still need proper backend headers for web.


    🔒 Security & Best Practices

    1. Never hardcode secrets (API keys, tokens) in frontend code.
    2. Use HTTPS—always. No exceptions.
    3. Handle errors gracefully—users hate silent failures.
    4. For auth, store tokens in secure storage (e.g., AsyncStorage in React Native + encryption).
    5. Consider aborting requests if the user navigates away (to prevent memory leaks):
    const controller = new AbortController();
    fetch('/api/data', { signal: controller.signal });
    
    // Later, if needed:
    controller.abort();
    

    🔄 Async/Await: Cleaner Syntax

    Both fetch and Axios work beautifully with async/await—making your code read like a story:

    async function loginUser(email, password) {
      try {
        const response = await axios.post('/login', { email, password });
        return response.data;
      } catch (error) {
        console.error('Login failed:', error.message);
        throw error;
      }
    }
    

    Much cleaner than .then() chains, right?


    🧪 Quick Comparison: fetch vs Axios

    Feature fetch() Axios
    Built-in ✅ ❌ (needs install)
    Automatic JSON parsing ❌ ✅
    Request timeout ❌ (needs workaround) ✅
    Interceptors ❌ ✅
    Browser support Modern only Broader (with polyfills)
    Bundle size 0 KB (native) ~5 KB

    👉 Use fetch if you want minimal dependencies.
    👉 Use Axios if you want developer ergonomics and advanced features.


    🎯 Final Thoughts

    Whether you’re building a sleek SaaS dashboard or a cross-platform mobile app, HTTP requests are your lifeline to the backend. And thanks to JavaScript’s ecosystem, you’ve got two rock-solid options that work almost everywhere.

    Start simple with fetch(). Scale up to Axios when you need more control. And always—always—handle errors like a pro.

    Now go make your app talk to the world. 🌐✨

    1 ответ Последний ответ
    1

    Категории

    • Главная
    • Новости
    • Фронтенд
    • Бекенд
    • Языки программирования

    Контакты

    • Сотрудничество
    • info@exlends.com
    • Наш чат
    • Наш ТГ канал

    © 2024 - 2025 ExLends, Inc. Все права защищены.

    Политика конфиденциальности
    • Войти

    • Нет учётной записи? Зарегистрироваться

    • Войдите или зарегистрируйтесь для поиска.
    • Первое сообщение
      Последнее сообщение
    0
    • Лента
    • Категории
    • Последние
    • Метки
    • Популярные
    • Пользователи
    • Группы