JAVASCRIPT
Converting JSON Object to URL-Encoded Form Data for POST Requests
Learn to convert a JavaScript object into a URL-encoded string (`application/x-www-form-urlencoded`) for POST requests, essential for integrating with specific legacy APIs.
const postData = {
firstName: 'John',
lastName: 'Doe',
age: 30
};
const formBody = Object.keys(postData).map(key => encodeURIComponent(key) + '=' + encodeURIComponent(postData[key])).join('&');
fetch('https://api.example.com/submit-form', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
},
body: formBody
})
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json(); // Or response.text() if not JSON
})
.then(data => console.log('Success:', data))
.catch(error => console.error('Error:', error));
How it works: Some APIs, especially older ones or specific third-party services, expect `application/x-www-form-urlencoded` for POST requests instead of JSON. This snippet demonstrates how to convert a JavaScript object into the required URL-encoded string format, then send it as the request body with the correct `Content-Type` header using the `fetch` API.