Having trouble with Javascript fetch() not receiving the correct JSON data from the local server

My Django backend is serving JSON data, but I'm encountering some unexpected results. When using curl 127.0.0.1:8000/posts/, the response includes:

[
{
"title": "This is a title",
"body": "Body :)",
"pub_date":"2020-11-25T13:36:57Z"
},
...
]

However, when running the following JavaScript code:

const API = '127.0.0.1:8000/posts/'
fetch(API).then(response => console.log(response))

The output differs, showing:

Response { 
type: "basic", 
url: "http://localhost:3000/127.0.0.1:8000/posts/", 
redirected: false, 
status: 200, 
ok: true, 
statusText: "OK",
 headers: Headers, 
body: ReadableStream, 
bodyUsed: false
}

This behavior is not as expected. Additionally, trying to parse the response with

.then(response => response.json())
leads to:

Uncaught (in promise) SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

Subsequent attempts such as:

fetch(API).then(response => console.log(response.headers))
fetch(API).then(response => console.log(response.text()))

Only result in:

Headers {  }
Promise { "pending "}
   <state>: "pending"

And further operations return the same error message regarding JSON parsing.

An update reveals that no new requests are being registered on the Django server log when refreshing the JavaScript page, despite successful GET requests made through curl.

Answer №1

To ensure the correct format, make sure your response is in JSON as shown below:

const API = '127.0.0.1:8000/posts/';
fetch(API)
    .then(response => response.json())
    .then(response => console.log(response));

Answer №2

In my opinion, the best approach would be to implement JSON.parse(response).

Alternatively, you could also try:

fetch(myRequest)
  .then(response => response.json())
  .then(data => {console.log( data })

Answer №3

One of the initial troubleshooting steps is to examine potential error logs in the backend system. When working with frontend and backend components on separate ports, it's essential to verify that there are no errors present, as CORS issues may arise.

If everything appears to be correct on the backend side, you can attempt to retrieve data using the following code snippet:

const API_ENDPOINT = '127.0.0.1:8000/posts/';
fetch(API_ENDPOINT)
    .then(response => response.json())
    .then(data => console.log(data));

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

Struggling to detect a click event within a VueJS application when using a bootstrap button-group

I am currently working on a VueJS project that includes a bootstrap button group... <div class="btn-group btn-group-xs pull-right" data-toggle="buttons"> <label class="btn btn-primary label-primary"> <input type="radio" name="options" i ...

Loading an ASP.net page on the client side

Can someone tell me the event for pageload on clientside? function onPageLoad() { setSelectedIndexTo(1); } I attempted to do this, however no changes occur. Appreciate any help. Thanks! ...

When attempting to use the jsonify method on a variable within an html file, the output is not displayed

Is it possible to store "jsonify" in a variable? I find the pure json format of "return jsonify(data)" unappealing, so I am looking for a way to enhance it using an HTML template with proper indentation. Here's the python code I have: from flask impo ...

The transmission of ContentType is unsuccessful

I'm having an issue with the code in my app. It seems that the content-type is not being sent. Is there a way to force it to be sent? $.ajax({ crossDomain: true, type: ...

How can the Node app utilize an HTML page to reference another JavaScript file? Ran into an unexpected syntax error: `Uncaught SyntaxError: Unexpected token '<

I'm trying to figure out how to call another script from an HTML page that is being served by my node project's localhost server. Here's the basic setup: index.js var http = require('http'); var fileSystem = require('fs' ...

Unable to display and conceal div elements

<ol class="novice"> <li> <p class="glava">HTML</p> <div class="vsebina"> <p>Hyper Text Markup Language (slovensko jezik za označevanje nadbesedila...</p> </div> </li> <li> ...

Tips for retrieving numerical values from JSON paths using Scala

I just received the following response: { "code" : 201, "message" : "Your Quote Id is 353541551" } To extract the number 353541551 from the above response, I attempted to use some basic Scala code snippets. Here's what I tried: .check((status i ...

Leveraging the power of express, employing the await keyword, utilizing catch blocks, and utilizing the next

I am currently developing an express JS application that follows this routing style: router.post('/account/create', async function(req, res, next) { var account = await db.query(`query to check if account exists`).catch(next); if (accoun ...

How to use AJAX to retrieve the text content of an HTML option value?

I have a script that displays a list of values, which I want to write: <option th:each = "iName : ${iNames}" th:value = "${iName}" th:text = "${iName}" th:selected="${selectedIName == iName}" In addition, I have the function setSelectedName in my .j ...

Tips for maintaining the data on a page continuously updating in AngularJS

I have this code snippet: $cookieStore.put('profileData', $scope.profileData); var profileData = $cookieStore.get('profileData'); $scope.init = function(){ var profileData = $cookieStore.get('pr ...

Error: The studentsList is not iterable. Issue encountered during Jasmine Unit Testing in Angular 2

How can I effectively test the forEach loop in jasmine with karma? Below is the code for the component: getData(studentsList:any, day:any, game:any){ let strength:any; let location:string; if(studentsList){ studentsList.forEach( value =& ...

Issue: Encountered a problem when attempting to encode the data type ([object Object]) into a Firestore Value while using Node

While attempting to insert a document with the geopoint dataType in firestore using the following instance: new firebase.firestore.GeoPoint(latitude, longitude) I encountered the following error. ...

Ways to identify an element within a webpage

I'm currently working on creating a chrome extension that can detect the presence of specific elements on a webpage. The goal is to have this extension automatically run every time a new page is opened and display a popup message if the element is fou ...

Extracting data from a webpage's dynamic table using Python with Selenium and

I am planning to extract the data from the JavaScript tables found in the following link: import codecs import lxml.html as lh from lxml import etree import requests from selenium import webdriver import urllib2 from bs4 import BeautifulSoup URL = &apo ...

Definition of a Typescript Global.d.ts module for a function that is nested within another function

Simply put, I have a npm module that exports a function along with another function attached to it: // @mycompany/module ... const someTool = (options) => { // do some cool stuff }; someTool.canUseFeature1 = () => { return canUseSomeFeature1(); ...

I can't seem to get the post method to work properly for some unknown reason

Hello there, I am encountering an issue while trying to submit a form on my website using the post method. For some reason, it keeps returning a null value. However, when I send data not through the form but instead by reading axios, it works perfectly fin ...

Leverage the URL parameter with variables in HTML using AngularJS

I'm facing the same issue as yesterday: trying to extract and utilize parameters from the URL within my HTML page using AngularJS. What am I doing wrong? The parameter I need to work with is: https://url.com/index.html?user I aim to retrieve the "u ...

Transforming JSON Object to a Different Object using Mule ESB

My current process is as follows: <?xml version="1.0" encoding="UTF-8"?> <mule xmlns:json="http://www.mulesoft.org/schema/mule/json" xmlns:db="http://www.mulesoft.org/schema/mule/db" xmlns:tracking="http://www.mulesoft.org/schema/mule/ee/trackin ...

Retrieve data from a JSON file using Ajax and jQuery

I have a JSon file that contains information about some matches: [{ "id": "2719986", "orario": "00:30", "casa": "Bahia", "trasferta": "Internacional" } , { "id": "2719991", "orario": "02:00", "casa": "Palmeiras", "trasferta": "Botafogo RJ" }] I'v ...

Create a PDF file discreetly

Currently, I am working on a classic asp page that generates a PDF and serves it to the browser. My goal is to create a loading page that preloads the PDF in the background before presenting it to the user, along with a visually appealing indication of ong ...