在添加 next-intl 后调用现有 Stripe 端点时,Fetch 返回“404 Not Found”

问题描述 投票:0回答:1

总结一下:我目前正在做一个react/next 电子商店,并使用stripe 来处理付款。 Stripe 提供可以在后端创建的结账会话,并在创建后自动在付款表单上重定向用户。

需要注意的是:我让它自己工作得很好,但我最近在我的应用程序上添加了语言功能,突然无法调用处理此结帐的 api 端点,并返回 404 未找到错误。 ..

我的 api 文件夹如下所示:

api
-> checkout
  -> route.ts
-> get-stripe-products
  -> route.ts
-> stripe-webhook
  -> route.ts

我使用以下在单击按钮时激活的函数来调用订单页面上的结账端点:

const checkout = async () => {
    await fetch("/api/checkout", {
      method: "POST",
      body: JSON.stringify({ products: cart }),
    })
      .then((response) => response.json())
      .then((response) => {
        if (response.url) {
          //response.url contain the success or failure url from transaction
          window.location.href = response.url;
        }
      });
};

现在这里是奇怪的部分:试图找到问题,我已经尝试过我的端点,通过在这个精确的获取中调用每个端点,这是我在网络选项卡(F5控制台)中得到的响应我的页面:

->

fetch("api/checkout",...)
:

Request URL: http://localhost:3000/api/checkout
Request Method: POST
Status Code: 404 Not Found

->

fetch("api/get-stripe-products,...)
:

Request URL: http://localhost:3000/api/get-stripe-products
Request Method: POST
Status Code: 405 Method Not Allowed

(这是正常的:get-stripe-product是GET方法,至少405表明提取找到了文件)

->

fetch("api/stripe-webhook,...)
:

Request URL: http://localhost:3000/api/stripe-webhook
Request Method: POST
Status Code: 200 OK

我认为问题可能是找不到 api 文件夹,但这表明情况并非如此......

所以基本上,我不明白为什么我的结账端点似乎无法通过提取找到。

再次,在添加语言处理(使用 next-intl)之前的我的应用程序版本上,相同的代码片段正确地启动了条带结帐会话,并且我被重定向到付款表单,没有任何问题。

关于我的应用程序版本之间的代码差异:

  • 我显示的代码片段在版本之间完全相同
  • checkout/route.ts文件几乎没有变化,我只修改了stripe.checkout.session对象的success_url和failure_url;如果错误来自这里,我认为它不会返回 404,而是返回特定错误。而且这不像是读取文件内的代码,因为从端点调用中抛出了 404

有任何线索说明造成这种情况的原因吗?

stripe-payments http-status-code-404 fetch-api endpoint next-intl
1个回答
0
投票

比预期更快地发现了问题:

关于我正在做的语言实现的更多细节,因为问题来自这里:使用 next-intl,所有需要以多种语言存在的页面都必须放在 [locale] 文件夹中,这会添加一个参数在 url 地址中(例如:在我的情况下,https://domain/page 中的所有页面都变为 https://domain/fr/page)

相应地,我在调用 checkout.session 的结账端点中更改了成功和失败 url,因为我需要将 url 调整为原始语言:

const session = await stripe.checkout.sessions.create({
line_items: stripeItems,
mode: "payment",
shipping_address_collection: {
  allowed_countries: ["FR", "GB"]
},
success_url: `${pathOrigin}/${locale}/success`,
cancel_url: `${pathOrigin}/${locale}/failure`

})

区域设置由以下行启动:

const locale = await getLocale()

getLocale是next-intl的后端函数,用于获取语言参数。

好吧,事实证明你不能在 api 端点中使用该行...不知道问题到底是如何出现的,但删除这一行立即解决了我的 404 未找到问题。

为了仍然获取我的区域设置变量,我更改了订单页面上的请求正文,以包含区域设置参数:

const checkout = async () => {
await fetch("/api/checkout", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify({ products: cart , locale}),
})

区域设置由 :

发起
const locale = useLocale();

useLocale 相当于 getLocale 的前端。

如何在 api/checkout/route.ts 中提取我的请求:

  const { products, locale } = await request.json();

这意味着问题源于 next-intl...我很好奇为什么会抛出 404 错误,但是嘿,希望没有其他人在这个愚蠢的问题上花费 4 个小时

© www.soinside.com 2019 - 2024. All rights reserved.