Tiny Frontend Logo
Posts 0130

On This Page

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.

Subscribe to read the full content

* Free subscribe to enjoy full content access.
* You can cancel anytime with 1-click.

Read Next

0129

Data Fetching from the Server

Do you know what AJAX is? It seems to be an "old" concept today, it allows us to use JavaScript to send asynchronous data requests to the server and update the rendering of the page locally.

Data Fetching from the Server
0128

JavaScript Currying

The first time I heard the term Currying was during a job interview preparation. Fortunately, the interviewer did not ask me any questions about it.

JavaScript Currying
0127

FormData in JavaScript

The most common way of sending data to the server in a network request is by using a JSON object. But, in some cases, JSON maybe insufficient to transmit the data.

FormData in JavaScript
0126

HTTP Status Code for SEO

When a browser sends a request, the server responds with a corresponding HTTP status code, whether the request can be fulfilled or not.

HTTP Status Code for SEO
0125

Data Transfer with WebSocket

You're probably already familiar with using the HTTP protocol to retrieve data from servers. However, in addition to HTTP, browsers also provide another networking protocol to meet more advanced communication needs: WebSocket.

Data Transfer with WebSocket
0124

Permissions on a Webpage

Your website cannot readily use some services like camera, microphone, location, etc. on the user device. For security reasons, the websites need to specifically request for permissions from the user to use these services. In this post, let's learn how to handle these permissions on a webpage.

Permissions on a Webpage