node.js - Stripe Checkout 示例从 localhost 遇到 CORS 错误
问题描述
我正在尝试使用此处给出的说明集成 Stripe Checkout,https: //stripe.com/docs/payments/accept-a-payment?integration=checkout for node。
我已按照他们的指示进行了发球,并使用我帐户中的实际(测试)密钥更新了示例中的 API 密钥。
我在前端使用 React 并在后端表达。我启用了cors。
从 React 到后端的请求成功,并且预检请求开始进行条带化。来自条带的预检响应是 403,实际请求因 CORS 错误而被阻止 -PreflightMissingAllowOriginHeader
后端代码(最少)
const express = require("express");
const app = express();
const cors = require("cors");
const stripe = require("stripe")(
process.env.STRIPE_SECRET_KEY
);
app.use(
cors({
origin: ["http://localhost:8000", "https://checkout.stripe.com"],
})
);
app.post("/create-checkout-session", async (req, res) => {
console.log('getting here 1')
const session = await stripe.checkout.sessions.create({
payment_method_types: ["card"],
line_items: [
{
price_data: {
currency: "usd",
product_data: {
name: "T-shirt",
},
unit_amount: 2000,
},
quantity: 1,
},
],
mode: "payment",
success_url: "http://localhost:4242/success.html",
cancel_url: "http://localhost:4242/cancel.html",
});
console.log('getting here 2')
res.redirect(303, session.url);
});
app.listen(4242, () => console.log(`Listening on port ${4242}!`));
前端代码
handleClick = () => {
const res = fetch(`${process.env.BACKEND_API_URL}/create-checkout-session`, {
method: 'POST',
headers: {
"Content-Type": 'text/html'
}
})
}
解决方案
以下是我在尝试调试时学到的一些东西。
- Stripe checkout 使用 AWS Cloudfront,它不允许选项请求(根据 Stripe 的配置)
- 当我将前端中的请求类型更改为
text/plain
. (是的,没错,在我的服务器返回带有 Stripe 的 url 的 303 后,Chrome 不会向 Stripe 发送 OPTIONS 请求) - 使用 React 时最好避免重定向
这是分别解决问题的更新的后端和前端代码
app.post("/create-checkout-session", async (req, res) => {
const session = await stripe.checkout.sessions.create({
payment_method_types: ["card"],
line_items: [
{
price_data: {
currency: "usd",
product_data: {
name: "T-shirt",
},
unit_amount: 2000,
},
quantity: 1,
},
],
mode: "payment",
success_url: "http://localhost:8000/success",
cancel_url: "http://localhost:8000/cancel",
});
res.json({url: session.url}) // <-- this is the changed line
});
handleClick = async () => {
const res = await fetch(`${process.env.BACKEND_API_URL}/create-checkout-session`, {
method: 'POST',
headers: {
"Content-Type": 'application/json'
}
})
const body = await res.json()
window.location.href = body.url
}
推荐阅读
- sql - 将多个表中的数据合并到一个列中
- python - 了解 scipy.ndimage.filters.convolve 函数
- ios - UIButton initWithFrame:CGRectMake 在 Xcode 9.3 中不起作用
- php - 在 Windows 上为 Laravel 设置 Xdebug
- nginx - 从站点 url 隐藏 .html 文件扩展名
- vb.net - 在本地制作全局变量
- machine-learning - 一种轻便而准确的分类器,可在来源有限的设备上使用
- python - 更新 Tkinter 进度条
- javascript - 我应该如何解析 Highcharts 的 dateTime?
- r - 按行索引和列标签合并