JavaScript·100 questions

How to make a POST request with fetch?

Answer

To send data to the server using the modern Fetch API, you need to pass a second argument to the fetch function — a configuration object containing the method, headers, and request body. A standard POST request looks like this: fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }). This approach allows you to pass structured data previously serialized into JSON format using the JSON.stringify method.

It is extremely important to correctly specify the Content-Type: application/json header in the headers object so that the backend server understands the format in which the request body is passed and can parse it correctly. If your goal is to upload files to the server, such as images or documents, the FormData object is used instead of JSON. In this case, a FormData instance with added files is passed in the body, and the browser automatically sets the correct multipart/form-data header along with a boundary marker.

After sending a POST request, you get a promise with a response object from which you can extract data using constructions like await response.json(). However, before doing this, it is strongly recommended to check the success of the operation via the response.ok property or the response.status condition. Remember that fetch does not consider status 400 or 500 to be a promise error, so manual checking of response codes will protect your application from unexpected failures when processing incorrect data on the server.

Was this answer helpful?

More questions in this topic

Related questions from other topics