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