Web Development

Cross Domain JSON Requests

Correctly configuring CORS for content-type: application/json

Joe Honton
JavaScript Fanboi
Published in
4 min readMar 29, 2021

--

The use of dynamic requests to backend servers is prevalent in modern web applications. Despite its commonplace nature, there are some gotchas that trip up even experienced developers.

TL;DR

In order to successfully preflight a JSON-encoded request to a different domain, the browser’s fetch request must include the HTTP header access-control-request-headers: content-type.

In order to signal that a JSON-encoded request from a different domain is permitted, the remote server must be correctly configured to respond with the HTTP header access-control-allow-headers: content-type.

Basic CORS rules

Before getting started, let’s review when Cross Origin Resource Sharing (CORS) is required.

  • CORS is only used when a web page needs to access something that is hosted on a different domain.
  • CORS is never used for HTTP requests made with the methods: GET, HEAD or OPTIONS.
  • CORS is a browser-to-server protocol. It uses HTTP for communication, but HTTP per se knows nothing about CORS. Because of this, requests sent via cURL, or tools like…

--

--