Essential CSS
JavaScript Roadmap
Learn JavaScript
Mastering Web Typography
Practical Astro
Understanding Async JS
Unorthodox Tailwind
API Masterclass
Build and Deploy
The Beginner Freelancer
Real World Node
Profile Billing Logout
Understanding Async JS
Lesson Plan
  1. Introduction
    1. What is Asynchronous JS?
    2. Callbacks are not automatically asynchronous
    3. What is an API?
    4. Evolution of HTTP APIs
    5. Ajax vs Asynchronous JavaScript
  2. Fundamental Concepts
    1. How to fetch resources
    2. Using XHR
    3. Using the Fetch API
    4. Using libraries
    5. Core JavaScript concepts
    6. Understanding Promises
    7. Understanding Async Functions
    8. Understanding the Event Loop
    9. Understanding JSON
    10. Async JS Best Practices
    11. Using Optimistic UI
  3. Understanding Rest API
    1. Diving into Rest APIs
    2. The Rest Architecture
    3. The Rest Structure
    4. Anatomy of a Request
    5. What's an endpoint
    6. Request methods
    7. Understanding request headers
    8. Understanding the request body
    9. Authentication
    10. Basic Authentication
    11. Bearer Authentication
    12. Authenticating with API keys and API Secrets
    13. Cross Origin Resource Sharing
    14. Anatomy of a response
    15. HTTP Statuses
    16. Response headers
    17. The response body
    18. Handling Errors
    19. Reading API documentations
    20. Understanding Curl
  4. Node Basics
    1. Why we are using Node
    2. Command Line Basics
    3. Installing Node
    4. Managing dependencies
    5. Using ES Modules in Node
    6. Using Node
    7. Restarting the server automatically
    8. Sending requests via Node
    9. Protecting API keys and secrets
  5. Building a server
    1. What's a server
    2. Building a simple server with Express
    3. Two kinds of servers
    4. API Server architecture
    5. Handling routes
    6. Understanding Middlewares
    7. Enabling CORS
    8. Receiving data
    9. Sending responses
    10. Handling errors in Express
    11. Using the server as a proxy
    12. Minimum viable server
  6. Open Authorization
    1. Open Authorisation (OAuth)
    2. Authenticating with Access Tokens
    3. Obtaining Access Tokens
    4. Public and Confidential Clients
    5. Authorisation Code Grant
    6. Understanding scope
    7. Proof Key for Code Exchange (PKCE)
    8. PKCE with Twitter
    9. Dynamic state and `code_verifier`
    10. Saving the access token in cookies
    11. Passing access tokens to the browser
    12. Saving the access token in local storage
    13. Refresh Token Grant
    14. Device Code Grant
    15. Client libraries vs REST
  7. Building Social Media Logins
    1. Introduction
    2. Starter Files
    3. Creating SSL certificates
    4. Login in with Github
    5. Github: Saving the token to local storage
    6. Github: Persisting the login status
    7. Login with Twitter
    8. Twitter: Saving the token to local storage
    9. Twitter: Persisting the login status
    10. Twitter: Refreshing the access token
    11. Login with Facebook
    12. Facebook: Saving the token to localStorage
    13. Facebook: Persisting the login status
    14. Facebook: Refreshing the access token
    15. Login with google
    16. Google: Saving the token to localStorage
    17. Google: Refreshing the access token

Understanding the request body

4m:9s

The body is also called the payload. It contains the meat of the information you want to send.

Two things to note:

  • The body is only used for POST, PUT, and PATCH requests.
  • It is not used for GET and DELETE requests.

When you send information via the body, you need to make sure you set the correct Content-Type header to go with the information you’re sending.

Three Common Content Types

Most of the time, you will use one of these three types of content:

  1. application/json
  2. application/x-www-form-urlencoded
  3. multipart/form-data

Let’s go through each of them.

application/json

If you set Content-Type to application/json, you’re telling the server that you’re sending JSON data — and they should interpret it as such.

Sending application/json data

The body contain JSON data.

If you need to convert JavaScript to JSON, you can use JSON.stringify:

const data = { message: 'Hello World!' }
fetch('link-to-resource', {
method: 'post'
headers: {
'Content-Type': 'application/json'
}
body: JSON.stringify(data)
})

If you use zlFetch, you don’t have to set Content-Type or use JSON.stringify — zlFetch does this for you automatically.

const data = { message: 'Hello World!' }
// Using zlFetch
zlFetch('link-to-resource', {
method: 'post'
body: data
})

application/x-www-form-urlencoded

x-www-form-urlencoded what gets sent from a <form> element to a server if no JavaScript is involved.

<form method="post" action="/link-to-somewhere">
<input name="first-name" />
<input name="email" />
<button>Send!</button>
</form>

Browsers will extract values from the form and turn them into a url-encoded format. This is a format that can be pasted into a browser’s address bar.

For example:

These values will also be paired with their keys into a key=value format like query parameters. Here’s what the above values may look like:

Terminal window
first-name=Zell+Liew&email=hello%40gmail.com

Sending application/x-www-form-urlencoded data

If you want to send form-urlencoded data with JavaScript, you need to convert the form data into the form-urlencoded format.

First, you need to convert any key-value pairs into the form-urlencoded format.

You can do this with URLSearchParams

const data = { message: 'Hello World!' }
const searchParams = new URLSearchParams(data)
const formatted = searchParams.toString()
console.log(formatted)

Next, you add the formatted data to the body property.

If you’re using fetch, you can omit Content-Type because fetch sets Content-Type to application/x-www-form-urlencoded by default.

const data = { message: 'Hello World!' }
const searchParams = new URLSearchParams(data)
const formatted = searchParams.toString()
fetch('link-to-resource', {
method: 'post'
body: formatted
})

If you use zlFetch the process becomes simpler.

You can:

  • import a toQueryString function from zl-fetch.
  • Use toQueryString to convert JavaScript objects into a form-urlencoded format.
  • Set the form-urlencoded data as body.

If you pass a form-urlencoded value as body, zlFetch will help you set the Content-Type to application/x-www-form-urlencoded automatically.

import zlFetch, { toQueryString } from 'zl-fetch'
const data = { message: 'Hello World!' }
const formatted = toQueryString(data)
zlFetch('link-to-resource', {
method: 'post'
body: formatted
})

Let’s move on to the third Content-Type.

multipart/form-data

multipart/form-data lets you send data that can be split into multiple parts — this is useful for sending files and images.

If you’re building a form that sends multipart/form-data, you need to make sure you add the multipart/form-data encoding.

<form method="post" action="/formdata" method="post" enctype="multipart/form-data">
<input type="text" name="name" />
<input type="file" name="profile_picture"/>
<button> Upload </file>
</form>

Sending multipart/form-data with JavaScript

To send multipart/form-data with JavaScript, you need to add your data to an instance of FormData.

Here, you can use the append method.

const formData = new FormData()
data.append('message', 'hello-world')

Next, you can send the form data directly in both fetch and zlFetch. No need to worry about the Content-Type in both cases — it’s handled for you automatically.

const data = new FormData()
data.append('message', 'hello-world')
// Using Fetch
fetch('http://link-to-resource', { body: data })
// Using zlFetch
zlFetch('http://link-to-resource', { body: data })

Bonus: The easiest way to get data from a form element

The easiest way to get data from the form element is to pass the entire form into FormData.

const form = document.querySelector('form')
form.addEventListener('submit', event => {
event.preventDefault()
const data = new FormData(form)
})

If you want to convert this data into a JavaScript Object or the form-urlencoded formats, you can use the helpers that I’ve included in zlFetch.

// Converting FormData to object
import zlFetch, { toObject } from 'zl-fetch'
form.addEventListener('submit', async event => {
const formData = new FormData(form)
const data = toObject(formData)
console.log(data)
})
// Converting object to form-url-encoded
import zlFetch, { toObject, toQueryString } from 'zl-fetch'
form.addEventListener('submit', async event => {
const formData = new FormData(form)
const object = toObject(formData)
const data = toQueryString(object)
console.log(data)
})

That’s all you need to know about the request body!

Next, you’re going to learn about Authentication.

This is super important because you need to authenticate to use most real-world APIs.

Let’s go.