Tips for navigating JSON properties without encountering errors

I am currently facing an issue when trying to utilize the JSON data returned from a fetch on the backend without causing any errors.

The fetch operation runs smoothly and returns a JSON response if I exclude the problematic line below:

fetch("https://dash.stannp.com/api/v1/postcards/create?api_key=" + secret + "&", requestOptions)
    .then(response => response.text())
    .then(result => {
        let item = result
        console.log("item: " + item)
        //this line causes an error
        console.log("pdf: " + item.data.pdf)
        return (item)
    })

The console.log("item: " + item) line displays the following:

item: {
    "success":true,
    "data": {
         "pdf": "https:\/\/dash.stannp.com\/api\/v1\/storage\/get\/rum\/1588348478\/pdf-samples\/7476-cda247f3-c634-43bf-8d03-731908549fb1-A6-4add27e8-b08f-4495-846b-7d904e.pdf",
         "id":"0",
         "created":"2020-05-01T15:54:38+00:00",
         "format":"A6",
         "cost":"0.59"
    }
}

After this, the

console.log("pdf: " + item.data.pdf)
line, which immediately follows the first one, triggers an error.

I'm unsure of what I'm doing wrong and how I can properly use the pdf link. Any help would be appreciated.

In case it's relevant, I suspect that there might be some issues with promises as the return statement executes before the fetch operation is completed.

Here is the complete code in case it aids in understanding the problem:

export function previewStannpSingleCard2(card) {
    return getSecret("stannp_API")
        .then((secret) => {
            var myHeaders = {
                "Content-Type": "application/json"
            }

            var myBody = JSON.stringify({
                // data here...
            })

            var requestOptions = {
                method: 'POST',
                headers: myHeaders,
                body: myBody,
                redirect: 'follow'
            };

            fetch("https://dash.stannp.com/api/v1/postcards/create?api_key=" + secret + "&", requestOptions)
                .then(response => response.text())
                .then(result => {
                    let item = result
                    console.log("item: " + item)
                    //console.log("pdf: " + item.data.pdf)
                    return (item)
                })
                .catch(error => console.log('error', error));
         })
}

Thank you for your assistance.

Answer №1

Pay close attention to your code

.then(response => response.text())

You're requesting text, but treating it as JSON

.then(response => response.json())

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

What is the best method for sending an angularjs $http POST request when a user refreshes a page?

controller: app.run(function ($rootScope, $templateCache) { $rootScope.$on('$viewContentLoaded', function ($scope, $http) { $templateCache.removeAll(); alert("refreshing....."); $http({ url: '/an ...

Tips on injecting numerous dependencies into an AngularJS controller

I'm currently working on testing one of my controllers, but I've encountered an issue. The $LoginController object I created always ends up being empty, and all my methods are present in the scope object instead. When attempting to test the hasEr ...

JSON.NET parsing data without corresponding field names

While working on a VB.NET forms application and utilizing JSON.NET, I am fetching data from a third-party source in the form of simplified JSON displayed below. { "Venue": { "ID": "ABDDF", "Name": "My Place", "Address": { "Address1": " ...

The functionality of aria-expanded="true" is not functioning properly when accessed on mobile devices

I am facing an issue where "aria-expanded="true" does not work when the user closes the dropdown on mobile devices, but it works perfectly fine on desktop browser pages. Desktop <a class="notifLink" data-toggle="dropdown" aria-haspopup="true" id="noti ...

What strategies can be used to transfer data from the client side to the server side in Next.js version 13

In my current project using Next.js v13, I am facing an issue with client-side and server-side interaction. There is an API that provides the data I need. Initially, I fetched the data from this API by sending a request to the server-side of my application ...

JavaScript's reversible functions

Creating choropleth maps often involves the need for a custom function that can map dataset values to corresponding colors. For instance, if the data ranges logarithmically from 1 to 10,000, a function like this might be necessary: var colors = ["#ffffcc" ...

The Date function is consistently providing me with inaccurate values

Encountering datefields issue only on iPad, while it works fine on my PC using Chrome and Edge. Seeking insight from anyone who can help with this? Prior to getting 2000-01-03 00:00:00 alert("BEFORE --- "+formatedDate); formatedDate = new Da ...

Tips on customizing the appearance of React rendering components

<div> <h3>{this.props.product.name}</h3> <h3>{this.props.product.code}</h3> {this.renderColors()} <article> <div da ...

Angular offers the ability to configure HTTP headers for requests

I need to include a header named "access-token" in all of my http requests like this: var app= angular.module("MainModule", ["ngRoute"]); app.run(function($http){ $http.defaults.headers.common['access-token'] =ACCESSTOKEN; }) and in my ser ...

Retrieve the offsetTop value of an accordion following its collapse

My goal is to determine the exact position of a clicked accordion title after it has been clicked. The issue I am facing is that the movement of Bootstrap's accordion collapse and my jQuery function are triggering almost simultaneously. As a result, ...

Vuejs Error: The 'in' operator cannot be used for searching

I am facing an issue with my form and VueJS. Upon clicking the "Login" button, I intend to change the text on the button. However, instead of achieving this, I encounter an error stating 'cannot use 'in''. Below is the HTML code snippet ...

Fan Animation in CSS

I have three unique images that I would like to animate in a fan-like manner consecutively. I prefer not to merge the images in Photoshop, as I want them to be displayed one after the other. Here is the code snippet (dummy images are used): .bannerimg ...

Checking the selected state of a radio button using jQuery can be tricky

I currently have a form set up like this: <div class="form-radios"> <!-- OPTION #1 --> <div class="form-item form-type-radio"> <input type="radio" name="auswahl_radio" id="option1" class="form-radio" ...

Ways to properly release file descriptors in write streams

I'm currently working on a code snippet that showcases what I'm aiming to achieve: const fs = require('fs'); var stream = fs.createWriteStream('/tmp/file'); stream.once('open', function(fd) { for (var i = 0; i ...

Asynchronous JavaScript function within a loop fails to refresh the document object model (DOM) despite

I have been working on a function that utilizes ajax to retrieve instructions from a backend server while the page is loading. The ajax code I've written retrieves the instructions based on the number provided and displays them using the response.setT ...

Utilizing static classes in Express: A guide

As a newcomer to the realm of JavaScript, I am eager to develop a web application using the MEAN stack. To maintain some level of organization in my files, I intend to encapsulate all MongoDb-related operations within a static class and call it from my ap ...

I would appreciate it if you could clarify the functionality of the remainder operator in this

I find it puzzling how the == 0 is used in conjunction with the remainder part of the code. Take for instance (4+4) % 2 == 0, it seems like it should evaluate to 4, but this piece of code actually generates outputs like true, false, true, false, and so o ...

Function that returns an Observable

In my typescript code, I have a function that looks like this: getConfigurations() { let sessionConfig = sessionStorage.getItem('config'); if(sessionConfig) return of(sessionConfig); else { this.dataService.getRoute(& ...

Divinely favored - pay attention for each and every sound

Currently, I am utilizing node with the blessed tty library downloaded from NPM. Within this library, there is a method called "key" that I am using in the following way: blessed.key(['q', 'z'], function(ch, key) { //do something ...

Using the jQuery Selector with multiple IDs will yield different results compared to using a single ID selector

Initially, I set up some dropdown menus to determine which one has been selected and then load the elements with no issues. However, when I added a new set of dropdowns, my existing function started applying to this one as well because it was too broad. ...