- Sending JSON data from JavaScript to an API is one of the most common tasks in modern web development. Whether you’re submitting a form, creating a user, or saving data, the pattern is largely the same.
- This guide explains how to send JSON correctly, with examples using fetch, axios, and legacy APIs.
Quick Checklist Before Sending JSON:
Serialize the object:
- JSON.stringify(obj)
Set the correct header:
- Content-Type: application/json
Parse the response:
- response.json()
Handle CORS:
- Required for cross-origin browser requests
Example 1: Sending JSON with Fetch (Modern Approach):
async function createUser(user) {
const res = await fetch('https://api.example.com/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(user)
});
if (!res.ok) {
throw new Error(HTTP ${res.status});
}
return await res.json();
}
Usage:
createUser({ name: 'Subhankar', city: 'Bhubaneswar' })
.then(user => console.log('Created user id:', user.id))
.catch(console.error);
Why Fetch?
- Built into modern browsers and Node.js
- Promise-based
- Clean async/await syntax
- No external dependency
Example 2: Sending JSON with Axios:
import axios from 'axios';
async function createUser(user) {
const res = await axios.post(
'https://api.example.com/users',
user
);
return res.data;
}
Why Axios?
- Automatically sets Content-Type
- Automatically parses JSON
- Supports interceptors and retries
- Easier testing and error handling
Example 3: XMLHttpRequest (Legacy Support):
const xhr = new XMLHttpRequest();
xhr.open('POST', '/users');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = () => {
if (xhr.status >= 200 && xhr.status < 300) {
const data = JSON.parse(xhr.responseText);
console.log(data);
}
};
xhr.send(JSON.stringify({ name: 'A' }));
- ⚠️ Use this only for very old browser support.
What the Server Receives:
Headers:
- Content-Type: application/json
Request Body:
{
"name": "Subhankar",
"city": "Bhubaneswar"
}
In Node.js + Express, this is parsed using:
- app.use(express.json());
Pitfalls & Best Practices:
JSON.stringify Caveats:
- ❌ Functions are removed
- ❌ undefined is ignored
- ❌ Circular references throw errors Use try/catch or custom serializers for complex objects.
CORS:
- Browser requests to another origin require server headers: code: Access-Control-Allow-Origin
Error Handling:
- Always check response.ok
- Handle network failures separately
Security:
- Never expose secrets in frontend code
- Always use HTTPS
- Validate data server-side
Short Decision Guide:
| Tool | When to Use |
| -------------- | -------------------------------- |
| fetch | Native, modern, lightweight |
| axios | Cleaner code, auto JSON handling |
| XMLHttpRequest | Legacy browser support |
Final Thoughts:
Sending JSON correctly is less about syntax and more about discipline:
- headers, serialization, error handling, and security.
- Master this pattern once—and you’ll use it everywhere.
Top comments (0)