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

Enabling CORS

3m:29s

You can configure CORS by setting 3 headers:

  • Access-Control-Allow-Origin
  • Access-Control-Allow-Methods
  • Access-Control-Allow-Headers

All 3 headers are mandatory.

Setting headers

You can set headers with the res.set method.

function middleware(req, res, next) {
res.set(headerName, value)
}

About Access-Control-Allow-Origin

If a request comes from a browser, the Access-Control-Allow-Origin header lets you decide whether to accept the request.

Note

All requests from servers will be accepted because servers are not restricted by CORS.

Access-Control-Allow-Origin takes in two possible values:

  • A specific origin like http://localhost:8080
  • A wildcard (*) that accepts all origins

Here’s how you would allow requests from a specific origin:

app.use((req, res, next) => {
res.set('Access-Control-Allow-Origin', 'http://localhost:8080')
next()
})

Once you have this, you should be able to access your server from the client without encountering a CORS error.

// Frontend JS
zlFetch('http://localhost:3000').then(response => console.log(response.body))

When to accept all origins

You should only accept all origins if you’re building a public API that can be accessed by any client. If you’re not doing this, you should not allow all origins.

That said, here’s how you would accept all origins:

// Allow all origins.
// Do not use unless you're building a public API that can be accessed by any browser
res.set('Access-Control-Allow-Origin', '*')

Accepting multiple origins

Access-Control-Allow-Origin only takes in one origin value.

If you want to allow multiple origins, you need to create an array of whitelisted origins.

If the request comes from a whitelisted origin, you set Access-Control-Allow-Origin to that origin.

Here’s the code you need to do this:

app.use(function (req, res, next) {
const whitelistedOrigins = ['http://localhost:3001', 'http://localhost:8080']
const origin = req.headers.origin
const found = whitelistedOrigins.find(o => o === origin)
if (found) res.set('Access-Control-Allow-Origin', origin)
next()
})

About the other two headers

To understand the other two headers, you need to take a deeper dive into CORS and understand the difference between a normal request and a preflight request.

Understanding Preflight requests

A preflight request is a tiny request that is sent before the main request. It is used to check whether the server would accept the main request.

  • Preflight requests are only sent if the request is a complex request.
  • If the request is simple, the main request will be sent immediately instead.

Imagine calling a restaurant to check if you can book a table. That call is a preflight request.

Here’s the difference between simple and complex requests:

  • Simple requests:
    • They must be a GET, HEAD, or POST request
    • They must not contain any headers except for Accept, Accept-Language, Content-Language, Content-Type, and Range
    • The Content-Type header must be one of application/x-www-form-urlencoded, multipart/form-data, or text/plain only.
  • Complex requests:
    • They are requests that do not conform with all of the required rules for simple requests

Most API requests nowadays are complex requests because:

  1. They usually use the application/json content type.
  2. They usually require the Authorization header for authentication.

Access Control Allow Methods

Access-Control-Allow-Methods determines what methods can be used for the main request.

The default is GET, HEAD, and POST (which are allowed methods for a simple request).

For most APIs, you need to allow all the methods you’ve learned so far plus the options method (which is generally only used for preflight requests).

res.set(
'Access-Control-Allow-Methods',
'GET, POST, PUT, PATCH, DELETE, OPTIONS',
)

If the request method is OPTIONS, you also need to respond with a 200 status code to tell the client you’re accepting their request. Without this, a preflight request would fail.

if (req.method === 'OPTIONS') return res.status(200).end()

Access Control Allow Headers

Access-Control-Allow-Headers determines what headers are allowed in the main request.

You need to list out all the headers you want to accept here.

Minimally, your server should accept 2 headers:

  • Content-Type
  • Authorization
res.set('Access-Control-Allow-Headers', 'Content-Type, Authorization')

That’s all you need to know about enabling CORS for your server!

Note

Many people use the cors package to configure CORS.

You can do that too.

I just felt it was easier to set these headers manually after I learned about them.