Home > Net >  Vue router refreshing page instead of navigating to it. What is the difference between these 2 code
Vue router refreshing page instead of navigating to it. What is the difference between these 2 code

Time:02-02

I'm trying to click a "checkout" button that sends cart data to a backend and redirects me to an url the backend produces.

My code isn't working. It's giving me a valid url, but when I try to redirect to that url the page just refreshes and I don't get redirected anywhere.

I have a working version of the code, I tried to just copy paste it from another project but it didnt work. I tried to refactor it to work with my code, but I can't figure out how to make it work.


The top code is the working code, the code below it is my not working code. Can someone help me understand the difference? What is going wrong with my code? What is the difference between my code and the working code? How do I make it function like the working code?

Working

-Frontend

<script setup>
import { ref, onBeforeMount } from "vue";
import CheckoutSummary from "../components/CheckoutSummary.vue";
import CheckoutButton from "../components/CheckoutButton.vue";

// Reactive data
const isLoading = ref(false);
const cart = ref([]);

// Get the cart data
onBeforeMount(async () => {
  const response = await fetch("/api/shopping-cart").then((r) => r.json());
  cart.value = response.cart;
});

// Click handler for button
const redirectToStripe = async () => {
  isLoading.value = true;

  const response = await fetch("/api/create-checkout-session", {
    method: "POST",
  });
  const { url } = await response.json();

  window.location.href = url;
};
</script>

-Backend

// Create a Checkout Session
app.post("/create-checkout-session", async (req, res) => {
  // Make an array of just our Stripe Price ID and quantities
  const lineItems = USER_SHOPPING_CART.map((item) => {
    return {
      price: item.stripePriceId,
      quantity: item.quantity,
    };
  });

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

Not Working

-Frontend

<script setup>
import { computed } from "vue";
import { useRouter } from "vue-router";
import { useStore } from "vuex";

const router = useRouter();

// eslint-disable-next-line no-unused-vars, no-undef
const props = defineProps({
  isLoading: Boolean,
});

const store = useStore();
const cartItems = computed(() => store.getters.getCheckout);

const redirectToStripe = async () => {
  const { url } = 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());

  console.log("url=", url);
  router.go(url);
};
</script>

-Backend

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 });
});

CodePudding user response:

use router.push(url) instead of router.go(url)

when using vue router its a good practice to use router.push to navigate instead of location.href because the later may produce some unexpected behavior.

CodePudding user response:

router.go is a method to be used when you want to move 'x' number of pages forward of backward in your browsing history.

router.push is to navigate to a page by adding a new item in the browser history. But it is meant for pages inside your application. Ex - going from '/about' page to '/careers' page on the same website. That is why we give the relative path or a page name to the push method.

From what I can see you are trying to redirect to a completely different page. In that case you should use window.open to open the page.

If it is a link to a checkout page then it might be better to open in a new tab using window.open(url, '_blank')

  • Related