0
0
JavascriptHow-ToBeginner · 3 min read

How to Make POST Request in JavaScript: Simple Guide

To make a POST request in JavaScript, use the fetch function with the method set to POST and include the data in the body as a JSON string. Set the Content-Type header to application/json to tell the server you are sending JSON data.
📐

Syntax

The basic syntax for a POST request with fetch includes the URL, an options object with method, headers, and body. The body contains the data you want to send, usually as a JSON string.

  • method: 'POST' to specify the request type.
  • headers: Object to set request headers like Content-Type.
  • body: The data sent with the request, often JSON stringified.
javascript
fetch('https://example.com/api', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({ key: 'value' })
})
💻

Example

This example sends a POST request to a test API with JSON data and logs the JSON response.

javascript
async function postData() {
  const response = await fetch('https://jsonplaceholder.typicode.com/posts', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      title: 'foo',
      body: 'bar',
      userId: 1
    })
  });
  const data = await response.json();
  console.log(data);
}

postData();
Output
{ id: 101, title: 'foo', body: 'bar', userId: 1 }
⚠️

Common Pitfalls

Common mistakes when making POST requests include:

  • Not setting the Content-Type header to application/json, causing the server to misinterpret the data.
  • Forgetting to JSON.stringify the body data, sending an object instead of a string.
  • Not handling the asynchronous nature of fetch, leading to unexpected results.
javascript
/* Wrong way: Missing headers and body not stringified */
fetch('https://example.com/api', {
  method: 'POST',
  body: JSON.stringify({ key: 'value' }) // This is now stringified
});

/* Right way: Set headers and stringify body */
fetch('https://example.com/api', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ key: 'value' })
});
📊

Quick Reference

Remember these tips for POST requests in JavaScript:

  • Always use method: 'POST' in fetch.
  • Set Content-Type header to application/json when sending JSON.
  • Use JSON.stringify() to convert data to a string.
  • Handle the response asynchronously with async/await or .then().

Key Takeaways

Use fetch with method 'POST' and include data in the body as a JSON string.
Always set the 'Content-Type' header to 'application/json' when sending JSON data.
Convert your data to a string using JSON.stringify before sending.
Handle fetch responses asynchronously to get the server's reply.
Avoid sending raw objects or missing headers to prevent request errors.