If $http.post()
in AngularJS is sending incorrect JSON format, it often leads to issues on the backend like bad request (400) or the server not understanding the payload. Let’s go through the issue step-by-step and understand how to ensure $http.post()
sends correct JSON data.
Step 1: Understand How $http.post()
Works
Basic syntax:
$http.post(url, data, config);
url
: API endpoint.data
: The data you want to send (usually an object).config
: Optional, lets you customize headers, etc.
Step 2: What Is “Incorrect JSON Format”?
This could mean:
- Data is sent as a string instead of JSON.
- Content-Type is wrong (e.g.,
application/x-www-form-urlencoded
instead ofapplication/json
). - JSON keys/values are malformed.
- Data is not serialized correctly.
Step 3: Proper JSON Format Example
Correct usage:
$http.post('/api/user', {
name: 'John',
age: 30
}, {
headers: { 'Content-Type': 'application/json' }
});
This sends:
{
"name": "John",
"age": 30
}
Step 4: Common Mistakes and Fixes
Mistake 1: Not setting the Content-Type
By default, AngularJS sets:
Content-Type: application/json;charset=utf-8
If you’re manually changing headers and forget to set this, it might send data in a different format.
Fix: Ensure the header is explicitly set:
$http.post('/api/user', data, {
headers: { 'Content-Type': 'application/json' }
});
Mistake 2: Sending String Instead of Object
If you send a string instead of a JavaScript object, Angular won’t convert it to JSON.
Bad:
$http.post('/api/user', "name=John&age=30");
This sends form data, not JSON.
Fix: Send a JavaScript object:
$http.post('/api/user', { name: 'John', age: 30 });
Mistake 3: Manual JSON.stringify()
AngularJS automatically stringifies your object into JSON. If you do it manually and still set application/json
, the server might double-parse it or break.
Bad:
$http.post('/api/user', JSON.stringify({ name: 'John' }), {
headers: { 'Content-Type': 'application/json' }
});
Fix: Let Angular handle it:
$http.post('/api/user', { name: 'John' }, {
headers: { 'Content-Type': 'application/json' }
});
Mistake 4: Using $http.defaults.transformRequest
Wrongly
AngularJS uses transformRequest
to format data before sending. If you’ve overridden it globally or per-request, it might break JSON formatting.
Check this:
$http.defaults.transformRequest = []; // Wrong: disables default JSON transform
Fix: Remove custom transformRequest
unless absolutely needed, or ensure it properly stringifies:
transformRequest: [function(data) {
return angular.toJson(data);
}]
Mistake 5: Server Expects Different Format
Sometimes, the backend expects application/x-www-form-urlencoded
instead of JSON.
Example: PHP, .NET Web Forms, classic ASP.NET
Fix: Change data format and headers:
$http({
method: 'POST',
url: '/api/login',
data: $.param({ username: 'user', password: 'pass' }),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
Or use Angular’s $httpParamSerializer:
app.config(function($httpProvider) {
$httpProvider.defaults.transformRequest = [function(data) {
return angular.isObject(data) && String(data) !== '[object File]' ?
Object.keys(data).map(k => encodeURIComponent(k) + '=' + encodeURIComponent(data[k])).join('&') : data;
}];
});
Step 5: How to Inspect the Sent JSON
- Open Chrome DevTools → Network tab
- Make the request
- Click the request → check “Headers” tab
- See if
Content-Type
is correct
- See if
- Check the “Payload” tab
- Confirm the actual JSON being sent
Step 6: Debug Output
Add console logs before sending the request:
console.log('Sending:', angular.toJson(data));
And confirm the server is actually parsing JSON. If the server doesn’t have proper middleware to parse JSON (like body-parser
in Node.js), it will treat it as empty or invalid.
Final Best Practice Example
app.controller('MyCtrl', function($http) {
const user = {
name: 'Alice',
age: 25
};
$http.post('/api/user', user, {
headers: {
'Content-Type': 'application/json'
}
}).then(function(response) {
console.log('Success:', response.data);
}, function(error) {
console.error('Error:', error);
});
});
Final Checklist
- Is data a JavaScript object?
- Is Content-Type set to
application/json
? - Avoid using
JSON.stringify()
manually - Avoid overriding
transformRequest
unless necessary - Check server expects JSON format
- Use browser dev tools to confirm headers and payload