"Tips for retrieving properties from a JSON object that has been converted to a string

I'm facing an issue with retrieving the url from a response in my code. The goal is to use this url for navigation using the router function.

Here's the problematic code snippet:

const redirectToStripe = async () => {
  const response = await fetch(
    "http://localhost:5000/create-checkout-session",
    {
      method: "POST",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json",
      },
      body: JSON.stringify(cartItems.value),
    }
  )
    .then((response) => response.json())
    .then((response) =>
      console.log("stringied response", JSON.stringify(response))
    );

  const { url } = await response.json();
  console.log("url=", url);  <--------------Doesn't execute, no console.log() readout

  // window.location.href = url;
  // router.go(url)  <------- NEED TO FIX THIS AND UNCOMMENT;
};

The error I encounter is:

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'json') at redirectToStripe

Addtionally, the console log output is as follows:

stringied response {"url":"https://checkout.stripe.com/c/pay/cs_test_a1X3r92YtZfM9H"}

The url mentioned above is what I need to access and navigate to using the router function. How can I extract the value of "url" so that it can be used in the following line:

router.go(url)

The later console.log() for "url" never executes due to the json error (I believe), but it seems to be the same url as the stringified one above?


I'm unsure why I'm encountering this error or if it needs to be fixed since I am able to retrieve the required url. Could this error be related to the "Content-Type" header? Have I selected the correct one? Are there any other mistakes in my approach?


Furthermore, here is how the backend endpoint looks like for additional context:

app.post("/create-checkout-session", async (req, res) => {
  // Make an array of just our Stripe Price ID and quantities
  const lineItems = req.body.map((item) => {
    console.log("lineItems= ", item.item.priceId, item.item.quantity);
    return {
      price: item.item.priceId,
      quantity: item.item.quantity,
    };
  });

  const session = await stripe.checkout.sessions.create({
    mode: "payment",
    line_items: lineItems,
    success_url: `http://localhost:8080/success?session_id={CHECKOUT_SESSION_ID}`,
    cancel_url: `http://localhost:8080/`,
  });
  return res.send({ url: session.url });
});

EDITS

@pope_maverick

This code snippet:

const redirectToStripe = () => {
  const response = fetch("http://localhost:5000/create-checkout-session", {
    method: "POST",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
    },
    body: JSON.stringify(cartItems.value),
  }).then((response) => response.json());
  const {url} = response.json();
  // const { url } = await response.json();
  console.log("url=", url);

results in the error:

Uncaught TypeError: response.json is not a function

Answer №1

Don't forget to include the return statement in your previous .then callback function. Otherwise, your const response will be assigned a value of undefined.

const response = await fetch(
    "http://localhost:5000/create-checkout-session",
    // [...]
  )
    .then((response) => response.json())
    .then((response) => {
      console.log("stringified response", JSON.stringify(response))
      // ❗️ Make sure to return `response` here to avoid the Promise returning the value of `console.log`, which is `void`!
      return response
    });

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

Can you outline the distinctions between React Native and React?

Recently delving into the world of React sparked my curiosity, leading me to wonder about the distinctions between React and React Native. Despite scouring Google for answers, I came up short on finding a comprehensive explanation. Both React and React N ...

Modify the layout of a JSON data structure

Here is an example of an array: let array = [ {1: { "date": "2014-04-23 00:00:00", "volumetrie": "22458" }}, {2: { "date": "2014-05-02 00:00:00", "volumetrie": "30585" }}, {3: { "date" ...

What advantages does separating vendors bring to Laravel Mix?

My initial bundle size was 246kb, and I wanted to reduce it further. After researching, I came across the method of extracting Vue and jQuery using mix.extract(['vue', 'jquery']);. Implementing this in my webpack.mix.js file resulted in ...

Put Jest to the test by testing the appendFileSync function

I am currently working on creating a test for appendfilesync function. When using a logger, I noticed that one line of code is not covered in my tests. Below is the code snippet I am referring to (please note that I am using tslog for logging purposes): ex ...

Unable to include a JavaScript file within another JavaScript file

Currently, I am working on a project where I am utilizing Django for the backend and HTML/CSS/JS for the frontend development. On a specific HTML page, I am including two JS files: dom_creator.js and console_page.js. My goal is to access the functionaliti ...

Two interconnected queries with the second query relying on the results of the first

I am currently facing a challenge in my Phonegap (Cordova) application where I need to display a list of items, each requiring an additional query. Let me simplify it with an example scenario. Imagine a student can be enrolled in multiple courses and a co ...

Retrieving Data from a JSON File in ASP.NET MVC 4

After diving into learning ASP.NET MVC 4, I dabbled in some small projects... On my index page, my goal is to fetch a JSON file containing data and showcase it on the main page. In basic HTML and JavaScript, I utilize ajax for fetching or posting JSON da ...

What is the best way to transfer information from a view to a controller in Laravel using AJAX?

I am facing an issue with sending data from the view to the controller in Laravel version 7 I am sending data from a form and ul li elements I have an array of data in JavaScript Here is my HTML code: <ul name="ali" id="singleFieldTags&q ...

Having trouble configuring a basic express server to host a static JavaScript file

Struggling to set up a basic Express server with accompanying HTML and JS files. Despite multiple attempts, I can't get the JS file to properly load. index.js: const express = require("express"); const app = express(); const path = require ...

Modifying the nested data organization in Sequelize

I'm looking to adjust the data structure retrieved from an ORM query involving four tables. The product and category tables have a many-to-many relationship, with the product_category table serving as a bridge. Additionally, there's a fourth tabl ...

Convert a character column in a DataFrame to JSON format in R

I have a dataframe with one column formatted as a character, but it actually contains JSON data. I searched on Stack Overflow for similar scenarios related to JSON data, but didn't find any specific solutions. df <- read.table(text=" ...

show a notification once the maximum number of checkboxes has been selected

I came across this code snippet from a previous question and I'm interested in making some modifications to it so that a message can be displayed after the limit is reached. Would adding a slideToggle to the .checkboxmsg within the function be the mos ...

Create a basic Vue.js page using Flask as a single server

There are numerous examples on the internet showcasing applications built with Flask (API) and Vue.js (client). Since Vue is a single-page application (SPA), it makes sense to serve it with Flask as well. However, I have encountered difficulties in finding ...

The formatting of script sections in .vue files is done by Vetur, excluding the use of Prettier

In a new vue-cli 3.0 project with Typescript and ESlint, I have active plugins in my VSCode including Vetur and Prettier. Despite checking all available settings and trying different approaches, I am struggling to resolve the following issue: Prettier su ...

Troubleshooting problems with Window.postMessage()

When attempting to fetch data from different domains, I am facing an issue. However, if I run the code on the same server, everything works perfectly fine and I am able to retrieve the message. index.html: <head> <title>Test 1</title&g ...

Invoke the method in customButton component of fullcalendar

I've integrated a custom button into my fullcalendar: ngOnInit() { this.calendarOptions = { customButtons: { custom1: { text: 'Add event', click() { this.openModal(); } } }, height: 600, editable: t ...

Learn how to easily set a radio button using Angular 4 and JavaScript

It seems like a simple task, but I am looking for a solution without using jQuery. I have the Id of a specific radio button control that I need to set. I tried the following code: let radiobutton = document.getElementById("Standard"); radiobutton.checke ...

Update the div each time the MySQL table is refreshed

My website functions as a messaging application that currently refreshes every 500ms by reading the outputs of the refresh.php file. I'm looking to explore the possibility of triggering the refresh function only when the 'messages' table upd ...

What is the alternative method for reading an HTML text file in JavaScript without utilizing the input type file?

Within the assets folder, there is a text file containing HTML that needs to be displayed within a specific component's div. Is it possible to retrieve the contents of this file and assign them to a string variable during the ngOnInit lifecycle hook ...

The radio button in the HTML form is disabled when the user selects

I have two radio buttons labeled Billable "Y" and Billable "N". These radio buttons are linked to a database with corresponding values of "Y" or "N". If the user selects "Y" using the radio button, then the NonBillableReason text box should be disabled. ...