The JSON API fetch request is failing because of Cross-Origin Read Blocking (CORB) restrictions preventing data retrieval

I am struggling with the persistent issue of receiving the (settings.js:76 Cross-Origin Read Blocking (CORB) blocked cross-origin response) error whenever I use the fetch method to retrieve JSON data from an API. Below is the snippet of code that I am currently working with:

 function workUpdate() {
     let data = new FormData();
     let miles = $("radius").value / 1000;
     let zip = "";
     let cookies = document.cookie.split(";");
      for (let i = 0; i < cookies.length; i++) {
          let key = cookies[i].split("=");
          if (key[0].trim() == "zip") {
               zip = key[1];
          }
      }
      if (zip == "") {
          $("radius-error").innerHTML = "Please provide your zip code in the personal information tab."
      } else {
          let url = "https://www.zipcodeapi.com/rest/TrAEIfdiFRU4FNxY94su2FXgrXbCRud9mnfyWdubJSKM5Py7x0g5LjTTd46NXIo8/radius.json/" + zip + "/" + miles + "/mile";
            fetch(url, {mode:'no-cors'})
               .then(checkStatus)
               .then(JSON.parse)
               .then(handleWorkResponse)
               .catch(console.log);
      }
     
 }

function handleWorkResponse(response) {
     let locations = response[0]["zip_code"] + "-";
     for (let i = 1; i < response.length; i++) {
         locations += "-" + response[i]["zip_code"];
     }
     let data = new FormData();
     data.append("locations", locations);
     let url = "php/workupdate.php";
     fetch(url, {method: "POST", body: data, mode:'cors', credentials:'include'})
               .then(checkStatus)
               .then(function() {
                   location.reload();
               })
               .catch(console.log);
 }

Answer №1

UPDATE:

After careful consideration, it has been pointed out by KevinB in the comments that this pertains to a 3rd party API. Consequently, modifying headers on the server side is not a viable option. A workaround for this issue could involve relocating this request to your own backend system (essentially concealing it behind a call to your personal server). As server-to-server requests are not subject to the same-origin policy, there is no requirement to establish the Access-Control-Allow-Origin header when accessing data through your server. Moreover, since your website is initiating the request towards your backend, which shares the same origin, setting the Access-Control-Allow-Origin header is also unnecessary here.

The Resolution

As others have highlighted, this issue primarily stems from the server side. To address this, ensure that the Access-Control-Allow-Origin header is configured within your server's response object for the specific route involved.

If you're utilizing Express for your server implementation, you can achieve this by integrating

res.header('Access-Control-Allow-Origin', '*')
into the corresponding route. Using * allows requests from any URL. For enhanced security, consider substituting * with the precise URL of the site from which you intend to extract data via the API.

Understanding the Mechanism

This protocol serves as a protective feature implemented by browsers to reduce the risk of cross-site scripting incidents. For further insights, refer to resources such as this article and this source.

Answer №2

When it comes to using the API from , setting up client-side access is essential for smooth operation. After creating an account, navigate to App Management and click on setting up client-side access. Remember to add the domain from which you will be making requests.

If you encounter a CORS-related issue, it's important to safeguard your API key by not exposing it in javascript code. Instead, visit to generate a client key. This unique key will begin with js-XXXXXX.

Utilize your client key in the following manner: let url =

"https://www.zipcodeapi.com/rest/<js-your client key>/radius.json/" + zip + "/" + miles + "/mile";

Check out this sample code snippet:

const calculateDistance = async (e) => {
    
    e.preventDefault();

          axios.get('https://www.zipcodeapi.com/rest/js-0ir7ZAGOD9sL2aQr5D1l77MjHL57EEICJWkGoSVilUKsO17zicasBVfvOjt443280S4xcY/distance.json/99501/99950/mile')
          .then(function (response) {
            console.log(response); 
    
          })
          .catch(function (error) {
            console.log(error)
           
          });
    
 
      
      };

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Experiencing a Typescript issue while trying to set a string as the state of a React component with a specified TS type

I've defined a state in my React component for a specific data type called Color. \\ state const [messageSeverity, setMessageSeverity] = useState<Color>('success'); \\ TS type export type Color = 'success&ap ...

Transferring an object from the factory to the controller

I'm currently working on setting up a factory that sends an ajax request to an API and then returns a data object. Here is the code snippet I have written: app.factory('Test', function($http, $q) { var data = {response:{}}; var getM ...

Having trouble with jQuery functioning on mobile devices?

I'm experiencing an issue where this code works perfectly on my desktop, but not on my mobile device. I've tried using different browsers on my mobile, but the code still doesn't function. Any assistance would be greatly appreciated. var li ...

Utilizing Typescript to transform a JSON object into a Typescript class

Hi there, I am facing a challenge while trying to convert an array of JSON objects into a TypeScript class. Every time I try to assign a JSON object attribute to a TypeScript attribute, the method crashes. Here is the TypeScript interface I am working wit ...

Verifying Ethereum transactions using BlockCypher

I'm currently utilizing the Blockcypher API for handling ethereum transactions (). After successfully completing all the necessary steps in creating and signing the transaction, I encountered an error when attempting to push the transaction: Could no ...

Is it possible to utilize ng-class without needing a controller in AngularJS?

Hey there! I'm working on this main div that wraps around the body code: <main class="main"> </main> Each page has its own modifier for the main class: Error page: <main class="main main--error"> </main> Events page: < ...

How to invoke a custom JavaScript function within an ejs template

In an ejs file, I included my own JavaScript function which I intended to use within that file. However, the function is not working as it is declared as undefined. Below is how I declared the function inside the ejs file: //my ejs file <script> ...

Guide on extracting matching values from one object based on the properties of another object

Looking to iterate through the object below and extract author names based on matching titles with other objects. The goal is to create a new object for easier management. business1 { "type": "FeatureCollection", "features": [ { ...

Challenges with navigating in a compact JavaScript application utilizing only a library called page.js

Currently, I am delving into the workings of a small routing library designed for javascript applications called page.js. To better understand how it operates, I created a very basic app for personal learning. However, I am facing issues making it function ...

Master the Art of Crafting Unique URLs

I am developing a web page that requires me to call two queries, each requiring an ID. However, I'm unsure of the best way to pass these IDs in the URL. For instance, one query is for books and the other is for authors. Currently, I have considered tw ...

ReactJS does not trigger a re-render when changes are made to CSS

I'm curious about the reason why ReactJS does not automatically reapply CSS to child components even when componentDidUpdate() is called. I conducted a small demo where adding a new box doesn't change the color of existing boxes, even though the ...

Obtain the output of the msDropdown Jquery plugin

For my project, I am utilizing the json version of the msDropdown plugin which can be found at this LINK. I have a basic question regarding how to retrieve the value from the example page shown on that link. Although I am not very proficient in JavaScript ...

Exploring ways to evaluate distinct keys within a JSON file

I need to compare specific keys in two different JSON files. How can I remove all the unnecessary keys from the JSON file? For example, here is JSON file 1: { "score" : "100" } And here is JSON file 2: { "Tests": [ {"score":"100"} ] } My goal is to ex ...

Is there a method to prevent the repetition of this loop?

I have a question regarding my React app development. I am currently using useEffect to loop through six items every time, even when only one item has changed. How can I optimize this so that only the variable that was changed in the reducer function is ...

Update the div content to completely replace it with fresh data using Ajax

I'm currently working on implementing a currency switcher feature for my website, allowing users to toggle between two different currencies. The site is a reservation platform with a booking form displayed on the left side and the booking details occu ...

What is the process for acquiring a comprehensive catalog of Node.js modules?

Currently, I am working on integrating NPM functionality into my Node.js applications. My goal is to be able to analyze the node modules available on my system. When referring to a "module" in this context, it could either be an identifier like "fd" or a f ...

Transform object into JSON format

Is there a way to transform an object into JSON and display it on an HTML page? let userInfo = { firstName: "O", lastName: "K", email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2b44476b445b05484446">[ema ...

Navigating Date Conversion within Component in Angular 2 Application

Searching for a way to update the display of certain dates in my Angular 2 application, I encountered a roadblock. Using the date pipe in conjunction with string interpolation wasn't viable due to the structure of my template code: <input class="a ...

Progress4GL scripting language controlling the back-end with JavaScript managing the front-end

I am working on developing an application that uses front-end HTML and JavaScript along with back-end Progress4GL. For reference, I came across this documentation at (specifically Introducing AJAX and Introducing JSON). The example in the documentation d ...

Efficient method for quickly updating the color scheme of a grid of squares in JavaScript

Currently, I am developing a JavaScript game that features a 2D array of squares with background colors that update each frame. My current approach involves utilizing a borderless DOM table and setting the style.backgroundColor property of each cell every ...