Error: The JSON data contains an unexpected token "p" at the beginning. This error occurred during the

const displayQuote = document.querySelector(".quotes");

fetch(`http://quotes.rest/qod.js?category=inspire`)
 .then(function(response) {
     return response.json();
})
 .then(function(myJson) {
    console.log(JSON.stringify(myJson));
});

error message displayed on the console

Uncaught (in promise) SyntaxError: Unexpected token p in JSON at position 0 Promise.then (async) (anonymous) @ quotes.js:8

I am attempting to retrieve the quote and display it.

Answer №1

Make sure to include the content-type and accept parameters in the headers section

const quote = document.querySelector(".quotes");

fetch(`http://quotes.rest/qod.js?category=inspire`, {
  headers: {
    "Accept": "application/json",
    "Content-Type": "application/json"
  }
})
 .then(function(response) {
     return response.json();
})
 .then(function(myJson) {
    console.log(JSON.stringify(myJson));
});


Check out more on Fetch API usage here

Answer №2

The data being returned by this endpoint is not in application/JSON format, but rather in application/javascript. It appears to be utilized for JSONP requests, as it returns javascript code that continues the call chain when executed.

To interact with this endpoint, you must either use a library that supports JSONP like jquery, or implement the support yourself. https://en.wikipedia.org/wiki/JSONP

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

Why is my react-hook-form sending an array with no data when making an axios request?

Within a container, I have mui Chips that contain labels. The objective is to utilize these chips as selectors, using onClick to add the label values to a list that will be sent in an Axios request. This needs to be achieved without the use of a textfield, ...

Tips for configuring formik values

index.js const [formData, setFormData] = useState({ product_name: 'Apple', categoryId: '12345', description: 'Fresh and juicy apple', link: 'www.apple.com' }); const loadFormValues = async () => { ...

Ways to stop Bootstrap collapse from displaying depending on a certain condition in bs5 framework

I've been struggling to figure out how to prevent a collapsible panel from opening or showing if a specific value is null. Despite multiple attempts, I haven't had any success. HTML <a href="#" data-bs-toggle="collapse" da ...

Requesting information from a model using a JavaScript variable in a cshtml file in an ASP.NET application

Is there a way to use a JavaScript variable to retrieve a specific item from an array stored in a model? Below is a code snippet: function CreateCategoryList() { var limit = @(Model.CategoriesCount.ToString()); for (i=0; i<limit; ...

Refreshing HTML Form upon Submit using JavaScript

I've been searching through various discussions without any luck, but I'm encountering an issue with a form that successfully submits data to a Google Sheet, yet the input fields retain their content after submission. Here is the code: <form ...

TABULAOTR, The complete table calculation is failing to be retrieved

Apologies for any language mistakes, as I am Russian :)I am using Tabulator but facing an issue where the table footer is not being printed. I am also unable to retrieve data from the footer. The footer simply doesn't show up and I'm unsure of wh ...

Tips for distinguishing between 1 and 1.00 as equal, and 1.01 as not equal in Angular

How should the number 1 be treated when the decimals are zero, for example 1.000? In this case, an alert popup should appear indicating that the numbers are the same. The maximum length of the textbox should be 7 characters. For instance, 1 and 1.00000001 ...

Empty POST request detected in select2 form submission

Looking for some assistance to help steer me in the right direction. My professor is unable to provide guidance. I'm currently struggling with handling POST requests in my form for select2 multiple fields. The issue arises from a Yes/No flag that dete ...

JavaScript capable of storing vast quantities of data

Currently, I am receiving file chunks in byte format from my server and combining them into one variable on my frontend for downloading later. Unfortunately, I am unable to modify the server setup which sends files sliced into chunks. The issue arises whe ...

Creating a dynamic 2D image using HTML5 animation

As a beginner HTML5 developer, I have been exploring ways to create an animated image using multiple jpg files stored in a specific folder on my website. My goal is to design an animation of a rabbit running across the page when a user clicks on a button. ...

Is localStorage.getItem() method in NextJS components behaving differently?

I'm working on my nextjs application and I wanted to utilize the power of localstorage for storing important data throughout my app. Within the pages directory, specifically in the [slug].tsx file, I implemented the following logic: export default fu ...

update value asynchronously

My implementation involves a dialog controller: .controller('loadingDialogCtrl', function($scope, $mdDialog, $rootScope, loadingDialog) { $scope.loadingDialog = loadingDialog; }); In another controller, I use the dialog controller and manip ...

Error: cannot use .json data with `filter` method from WEBPACK_IMPORTED_MODULE_2__["filter"]

There seems to be an error occurring when attempting to retrieve data from a JSON file in the specific line of code selectedEmployee: employeeList.data.Table[0], An issue is arising with TypeError: _employeeList_json__WEBPACK_IMPORTED_MODULE_2__.filter ...

What is the most efficient way to loop through an array and send each item to a method, ensuring that all methods are executed synchronously?

I need to make a request method call that retrieves its own body as an array, which is one item within another array. To achieve this, I have to iterate over the parent array and pass each of its items to the request method for a new server request. I tr ...

The shade of grey on the curve appears instead of the usual red on the iPad. Any ideas on how to fix

I am having trouble creating a curve like the one shown below on my iPad. The color appears to be gray and does not work properly. Is this a bug with ChartJS or is there a solution to fix this issue? This problem occurs when the type value is set to "lin ...

Enhancing Rails: Tailoring the flash message to suit individual needs

I am embarking on my journey with ruby on rails and could use some guidance with the following scenario. In the application.html.erb file, flash messages are configured to fade out after a few seconds by default. <div id="message" class="modal alert a ...

Fluctuating price depending on the selected choice

Hello, I am in the process of updating the price based on the selection made from the options. I am unsure whether to use JavaScript or Ajax for this task and how to go about it. Can someone please guide me? <tr> <td width="160">Price:</td ...

Associating user input information with an AngularJS object

Currently, I am working on a project that involves inputting a user's ID, first name, and last name. Once the input is received, a user object is created and stored inside the logins array. My goal is to display each new user as the next item in an u ...

Guide to activating "Snapping" feature using the "Select" function in Openlayers 3

I have created an application using OpenLayers 3 that allows users to draw lines or points on a map and add tags to them. While the existing functions in OL3 are helpful for drawing and modifying features, I found it challenging to select the items I drew ...

Find all relevant employee information at once without the need for iteration

I have structured two JSON arrays for employee personal and company details. By inputting a value in the field, I compare both tables and present the corresponding employees' personal and company information in a unified table. <html> ...