Making a POST Request to the Server
In our previous post, we wrote about GET
requests using JavaScript's fetch() method. This is a simple use case where we pass in a url into the method. However, fetch()
also takes in a second parameter (optional) where we can pass in various request options.
In this post, we will be going through how we can control various settings using the request options parameter.
Request Options
async function postData(url = "", data = {}) {
const response = await fetch(url, {
method: "POST", // *GET, POST, PUT, DELETE, etc.
mode: "cors", // no-cors, *cors, same-origin
credentials: "same-origin",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
});
return response.json();
}
// Usage
postData("https://example.com/api/endpoint", { answer: 42 })
.then((data) => {
console.log(data);
})
.catch((error) => {
console.error("Error:", error);
});
Request options include but are not limited to:
method
Specifies the type of HTTP request to be made, other methods include GET
, PUT
, etc.
mode
Determines the CORS (Cross-Origin Resource Sharing) behavior. The possible values for mode are:
- cors: Allows cross-origin requests.
- same-origin: Allows requests only if the origin matches exactly.
- no-cors: Prevents CORS checks (useful for certain scenarios like service workers).
headers
Allows custom headers to be set for the request. In the above example, Content-Type
header is set to application/json
to indicate that the request will contain JSON data.
body
Contains the data to be sent in the request body. In the above example, JSON.stringify(data)
is used to convert the data object to a JSON string.
credentials
Specifies whether to include credentials such as cookies or HTTP authentication. The possible values are:
- same-origin: Includes credentials only for same-origin requests.
- include: Includes credentials for both same-origin and cross-origin requests.
- omit: Does not include credentials.
Uploading Multiple Files
In another previous post, we talked about sending a single file with user-input data using FormData in a HTTP request. We will be extending the use case to send multiple files.
Firstly, we can create a HTML input component like this.
<input type="file" multiple />
Adding the multiple attribute allows the form control accepts one or more values.
async function uploadPictures(formData) {
try {
const response = await fetch("https://example.com/posts", {
method: "POST",
body: formData,
});
const result = await response.json();
console.log("Success:", result);
} catch (error) {
console.error("Error:", error);
}
}
const photos = document.querySelector('input[type="file"][multiple]');
const formData = new FormData();
formData.append("title", "My Photo Album");
for (const [i, photo] of Array.from(photos.files).entries()) {
formData.append(`photos_${i}`, photo);
}
uploadPictures(formData);
We can retrieve all the files (or photos in this example) from the input component, iterate through each file and append it to the formData
with a unique key.