How to Make HTTP GET/POST Requests in JavaScript (for Web and Mobile)
-
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 Requestfetch('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 Requestfetch('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.headersspecify the data format (usually JSON).bodymust be a string—so we useJSON.stringify().
Option 2: The Powerhouse — AxiosIf 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 Axiosimport 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 Axiosaxios.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- Never hardcode secrets (API keys, tokens) in frontend code.
- Use HTTPS—always. No exceptions.
- Handle errors gracefully—users hate silent failures.
- For auth, store tokens in secure storage (e.g.,
AsyncStoragein React Native + encryption). - 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 SyntaxBoth
fetchand Axios work beautifully withasync/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:
fetchvs AxiosFeature 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 fetchif you want minimal dependencies.
Use Axios if you want developer ergonomics and advanced features.
Final ThoughtsWhether 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.


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