【问题标题】:Setting baseURL for axios for use with Stripe / React为 axios 设置 baseURL 以与 Stripe / React 一起使用
【发布时间】:2021-01-31 07:53:52
【问题描述】:

我目前正在尝试使用带有 React 的 Stripe 处理付款。但是按照教程,我得到一个错误 404,我的 api/payment_intents 没有找到。


const stripe = new Stripe('here is my key');

export default async (req, res) => {
  if (req.method === "POST") {
    try {
      const { amount } = req.body;
      // Psst. For production-ready applications we recommend not using the
      // amount directly from the client without verifying it first. This is to
      // prevent bad actors from changing the total amount on the client before
      // it gets sent to the server. A good approach is to send the quantity of
      // a uniquely identifiable product and calculate the total price server-side.
      // Then, you would only fulfill orders using the quantity you charged for.

      const paymentIntent = await stripe.paymentIntents.create({
        amount,
        currency: "usd"
      });

      res.status(200).send(paymentIntent.client_secret);
    } catch (err) {
      res.status(500).json({ statusCode: 500, message: err.message });
    }
  } else {
    res.setHeader("Allow", "POST");
    res.status(405).end("Method Not Allowed");
  }
};

这是 axios 的帖子

const { data: clientSecret } = await axios.post("../api/payment_intents", {
            amount: this.state.amount * 100
          });

我在另一篇文章中读到我需要设置一个 baseURL,但我不确定如何/这甚至意味着什么。任何帮助将不胜感激

更新:使用“localhost:3000/api/payment_intents”我能够得到关于 CORS 策略的不同错误消息

从源“http://localhost:3000”访问“localhost:3000/api/payment_intents”处的 XMLHttpRequest 已被 CORS 策略阻止:跨源请求仅支持协议方案:http、data、chrome、 chrome-extension, chrome-untrusted, https.

【问题讨论】:

    标签: reactjs axios stripe-payments


    【解决方案1】:

    像这样定义baseURL:

    let API = axios.create({
        baseURL: "http://base_url/api"
    })
    
    export default API;
    

    然后在你的 axios 帖子中:

    const { data: clientSecret } = await API.post("/payment_intents", {
        amount: this.state.amount * 100
    });
    

    通常,您还希望将 URL 作为环境变量传入。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-21
    • 2020-06-16
    • 2021-09-02
    • 2018-11-24
    • 2018-12-23
    • 1970-01-01
    相关资源
    最近更新 更多