Authentication error: The API data retrieval was disrupted due to an unexpected termination of input

I encountered an error while trying to fetch data from an API using JavaScript.

<button onclick="event.preventDefault(); getOdds()">Print odds</button>

JS

function getOdds() {
   const sportsKey = prompt("Enter the sports key:");
   const region = prompt("Enter the region (choices = uk, us, us2, eu, au):");
   const market = prompt("Enter the market (choices = h2h, spreads, totals, outrights):");
   const apiKey = 'APIKEY';
   let headers = new Headers();

   headers.append('Content-Type', 'application/json');
   headers.append('Accept', 'application/json');
   headers.append('Access-Control-Allow-Origin', '*');
   headers.append('Access-Control-Allow-Credentials', 'true');
   headers.append('GET', 'POST', 'OPTIONS');
   headers.append('apikey','apikey');

 fetch('https://apiurl/'+sportsKey+'/odds?apiKey='+apiKey+'&regions='+region+'&markets='+market+'', {
  mode: 'no-cors',
  credentials: 'include',
  method: 'GET',
  headers: headers
})
.then(response => response.json())
.then(json => console.log(json))
.catch(error => console.log('Authorization failed : ' + error.message));
}

Upon clicking the "Print odds" button, I encountered the following error:

Authorization failed : Unexpected end of input

How can I resolve this issue?

Answer №1

Here are some steps you can try to resolve the issue:

Step 1:

If the response you're receiving is not valid JSON (possibly null), you can attempt the following:

fetch('https://apiurl/'+sportsKey+'/odds?apiKey='+apiKey+'&regions='+region+'&markets='+market+'', {
  mode: 'no-cors',
  credentials: 'include',
  method: 'GET',
  headers: headers
})
.then(response => {
  return response.text()
})
.then((data) => {
  resolve(data ? JSON.parse(data) : {})
})
.catch((error) => {
  reject(error)
})

If obtaining the text does not result in an error, check for data existence and then resolve. Hope this helps!

Step 2 :

If Step 1 did not work, consider changing the mode to 'cors'

fetch('https://apiurl/'+sportsKey+'/odds?apiKey='+apiKey+'&regions='+region+'&markets='+market+'', {
  mode: 'cors', // update here 
  credentials: 'include',
  method: 'GET',
  headers: headers
})

I hope these suggestions address your inquiry :)

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

gulp.watch executes tasks without following a specific sequence

Objective Develop a gulp.watch task to execute other tasks in a specific sequence Why this is unique While many have referred me to How to run Gulp tasks sequentially one after the other, my query differs as it pertains to using gulp.watch instead of gu ...

Uncovering the deepest levels of nested arrays and objects in JavaScript without any fancy libraries - a step-by-step guide!

I have been struggling to find a solution to a seemingly simple problem. Despite searching through various sites and resources, I have not been able to figure out how to iterate over the innermost levels of a doubly nested data structure. I have tried usin ...

Gulp and Vinyl-fs not functioning properly when trying to save in the same folder as the source file due to issues with

After exploring a variety of solutions, I have yet to find success in modifying a file in place using Gulp.js with a globbing pattern. The specific issue I am facing can be found here. This is the code snippet I am currently working with: var fstrm = re ...

Convert this JavaScript function into a jQuery function

I currently have this JavaScript function: function removeStyle(parent){ var rmStyle = document.getElementById(parent).getElementsByTagName("a"); for (i=0; i<rmStyle.length; i++){ rmStyle[i].className = ""; } } Since I am now using ...

Using Vue.js to make asynchronous API requests using Axios

I am facing an issue with two versions of code, where the second version is not functioning as expected. I suspect it may be due to a contextual problem that I am unable to pinpoint. The first version of the code works fine: // Fist version (it works) met ...

Unable to update div CSS using button click functionality

I have been working on this HTML/CSS code and I am trying to change the style of a div using a JavaScript button click event so that the div becomes visible and clickable. However, despite my efforts, it doesn't seem to be working as expected. Whenev ...

Determine in a JSON array and add to an array object if the key is not found

I've got a JSON array like this: 0: {Id: "1", name: "Adam", Address: "123", userId: "i98"} 1: {Id: "2", name: "John", Address: "456"} The second object in the array doesn't have a userId key. How can I iterate through the array and add the ...

Multiple instances of Ajax drop-down effects are now available

On my website's staff page, I have implemented a dropdown menu using AJAX to display information about each member of the staff. The issue arises when attempting to open multiple dropdown menus on the same page - the second dropdown that is opened ten ...

Command not found: execute - firebase deploy

After deploying my Firebase function project, I encountered an error that said "missing script:build." I have tried to fix it on my own but have been unsuccessful. I would greatly appreciate any assistance Here is a screenshot of the error https:// ...

Using Angular Material datepicker in conjunction with Moment.js to serialize the moment objects for the backend - what's the

I am facing an issue with the date picker on the frontend using the moment adapter with the locale settings. While everything seems to be working fine with the dates on the front end, I am unable to convert them properly on the backend. The date is obtaine ...

Alert from Google Chrome about Service Worker

My situation involves using FCM for sending web notifications. However, I am encountering a warning and the notifications are not functioning as expected when clicked (i.e., opening the notification URL). Below is my Service-Worker code: importScripts(& ...

Utilizing browser's local storage to dynamically update text in buttons and panels

In my file, I have the following code snippet (I've removed other irrelevant code) <div data-role="panel" id="loc_panel"> <h2>Panel Header</h2> <p>info about this stop</p> </div> <!-- /panel --> < ...

The JSON data sent from the primary Electron process is arriving as undefined in the renderer

Currently delving into an Electron project to explore the technology. It's been a captivating and enjoyable experience so far as I work on creating a basic home controller for my IoT devices. However, I've encountered a minor issue. In my main.js ...

Can curly braces be utilized in the style section of Vue.js?

Can I utilize curly braces in the style section of vue.js to set a value? For instance .container { background: url({{ image-url }}; color: {{ color-1 }} } ...

how to use AngularJS filter and ng-options to format specific options as bold in a select dropdown

I am currently utilizing AngularJS ng-options to populate specific select elements. I am interested in bolding and disabling certain options. Despite trying to achieve this using the filter along with ng-options, I have been unsuccessful so far. While I ca ...

Update the multidimensional array function to ES6 syntax

I'm in the process of developing a function for my app and I'm curious if there's a more elegant way to implement it using ES6, without relying on two for loops. The goal is to create a multi-dimensional array that keeps track of x and y co ...

Filtering out duplicate names from an array of objects and then grouping them with separator IDs can be achieved using JavaScript

Imagine we have an array [ {id: 1, label: "Apple"}, {id: 2, label: "Orange"}, {id: 3, label: "Apple"}, {id: 4, label: "Banana"}, {id: 5, label: "Apple"} ] We want the output to be like this [ {id: 1~3~5, l ...

When the overflow-y property is set to hidden, the page unexpectedly scrolls to the top in Firefox

I have a javascript code that is responsible for opening modal popups on my website. It also manipulates the overflow-y property of the <html> element by setting it to hidden. Interestingly, in Chrome and IE, this functionality works as intended. The ...

Is a Page Refresh Required to Reload Routes in ReactJS?

I have created menu links labeled Home, About, What I Do, and Experience for my portfolio site using BrowserRouter. However, when I click on these links, the components do not load properly on the page; they only render correctly after a page refresh. This ...

Applying shadows to the outer edges of a View in React Native, without affecting the inner views

Here is a glimpse of my webpage layout https://i.sstatic.net/Y9WZZ.png I am attempting to apply a shadow only along the red line https://i.sstatic.net/hUou7.png I do not want the shadow to affect the inner elements, especially the text. Additionally, I ...