Sending a POST request

Hey ,

I'm thrilled to help you learn JavaScript. Unfortunately, you've landed on a page where you cannot access with your current purchase.

Please upgrade (use this link) access this content.

I'm super eager to help you learn more!

Sending a POST request

You can use a POST request to create a resource. Once the server gets your request, it updates a database that stores your information. Examples of POST requests include:

  1. Creating a user
  2. Creating an article
  3. Creating a comment
  4. Creating a todo item

POST requests require authentication. This means the server wants to make sure you are what it thinks you are. If you are not who it thinks you are, you cannot create a resource.

Authentication is an important process. If your bank doesn’t perform authentication, anyone can transfer money from your account into their account without your knowledge. That’s why requests need to be authenticated.

We’ll discuss authentication in a later lesson. For now, we’ll send our requests to a fake server that’s built for learning.

This server is called Typicode. The root endpoint you should use is https://jsonplaceholder.typicode.com.

Formatting your request body

Before you make a post request, you need to tell the server what data you are going to send over. When you make API calls, you’ll usually send one of these formats:

  1. JSON
  2. x-www-form-urlencoded

Formatting your request body as JSON

To tell a server you’re going to send JSON data, you need to set the Content-Type header to application/json.

To set the header in XHR, you can use setRequestHeader. This header must be set between the open and send calls.

const request = new XMLHttpRequest()
request.addEventListener('load', e => { /* Do something */ })
request.open('method', 'link')
request.setRequestHeader('Content-Type', 'application/json')
request.send()

To set the header in Fetch, you pass pass an object as the second argument. This object should contain a headers property.

fetch('some-url', {
  headers: {
    'Content-Type': 'application/json'
  }
})

Note: headers are case insensitive. You can set Content-Type or content-type. Both will work.

Before sending your request, you also need to format your body as JSON. You can use JSON.stringify to do so.

To send the body with XHR, you pass it into the send call.

const body = JSON.stringify({ key: 'value' })
request.send(body)

To send the body with Fetch, you set the body property.

fetch('some-url', {
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    key: 'value'
  })
})

Formatting your body as x-www-form-urlencoded

x-www-form-urlencoded data is data that can be sent as a URL. Query parameters are an example of url encoded data. They look like this:

param1=value1&param2=value2

If you need to send values that contain special characters (like slashes or spaces), you need to encode them such that they can be read through the url.

To do so, you use encodeURIComponent.

const encoded = encodeURIComponent('http://google.com')
console.log(encoded) // http%3A%2F%2Fgoogle.com

To tell a server you’re going to send url encoded data, you set Content-Type to x-www-form-urlencoded.

// Sending url encoded data with XHR
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
request.send('param1=value1&param2=http%3A%2F%2Fgoogle.com')
// Sending url encoded data with Fetch
fetch('some-url', {
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  },
  body: 'param1=value1&param2=http%3A%2F%2Fgoogle.com'
})

Sending a post request

You need to set the method to post to send a POST request. You can do this when you call open with XHR.

request.open('post', 'some-url')

You can set the method as a property of the second argument in Fetch:

fetch('some-url', {
  method: 'post'
})

Try sending a POST request to the Typicode. Here’s an example:

fetch('https://jsonplaceholder.typicode.com/posts', {
  method: 'post',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    title: 'This is my first article',
    body: 'A shameless plug about myself'
  })
})
  .then(r => r.json())
  .then(d => console.log(d))

The server will let you know if your request succeeds. If it succeeds, it will send you one of the two responses:

  1. A success message
  2. A response that contains information about the created resource (like in the image below)
A response for a post request
A response for a successful post request

Note: This resource isn’t created on Typicode. They’re faked as if they were created.

Sending put or patch request

PUT and PATCH requests are used to update a resource on the server. They also require authentication. To send a PUT or Patch method, you set the method to put or patch.

When you send a PUT or Patch request, you also need to tell the server what resource you want to update or delete. This is often done through the path.

Here’s an example where we update the 50th post with Fetch

fetch('https://jsonplaceholder.typicode.com/posts/50', {
  method: 'put',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    title: 'This is my 50th article',
    body: 'A poem about how JavaScript can save lives'
  })
})
  .then(r => r.json())
  .then(d => console.log(d))

Sending a delete request

To send a delete request, you use the delete method. You also need to tell the server what resource you want to delete.

fetch('https://jsonplaceholder.typicode.com/posts/1', {
  method: 'delete'
})

Exercise

Send the following requests to Typicode. Here’s a link to the documentation if you need it.

  1. Send a GET Request to Typicode to request for the 56th post
  2. Send a POST request to create a post
  3. Do this with XHR
  4. Do this with Fetch
  5. Send a PUT request to change the 23rd post
  6. Do this with XHR
  7. Do this with Fetch
  8. Delete the 90th post