In this lesson, you will learn how to send data with Fetch and handle API errors in JavaScript.
Sending data using Fetch allows you to communicate with servers. For example, when you submit a form online, your data is sent through an API. This makes it an essential part of web development.
File: sendData.php
// sendData.php
const url = 'https://jsonplaceholder.typicode.com/posts';
const postData = { title: 'My Post', body: 'This is my first post.', userId: 1 };
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(postData),
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error('There has been a problem with your fetch operation:', error));
Expected Output:
{
"title": "My Post",
"body": "This is my first post.",
"userId": 1,
"id": 101
}
In our code, we use fetch() to send a POST request. The method: 'POST' line specifies we’re sending data. headers tells the API we’re using JSON. JSON.stringify(postData) converts our JavaScript object into a JSON string.
Now, create a JavaScript function that sends user information (name and email) to an API endpoint. Use the same principles learned here.
// submitUserData.php
const userApiUrl = 'https://jsonplaceholder.typicode.com/users';
function submitUserData(name, email) {
const userData = { name: name, email: email };
fetch(userApiUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(userData),
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
}
// Call the function
submitUserData('John Doe', 'john@example.com');
response.ok is true. It helps to catch server errors.JSON.stringify(). Bad format leads to errors in API.