Node.js用node-fetch调用Stripe API报Cannot use 'in' operator错误求助
问题解决方案
错误根因
- 第一个
TypeError: Cannot use 'in' operator to search for 'signal' in报错:fetch 第二个入参要求接收配置对象,代码中错误传入了JSON.stringify(params1)得到的字符串,运行时尝试在字符串上查找配置属性signal直接触发异常。 - 后续接口报错:即使传入原始配置对象
params1也会请求失败,因为Stripe v1 API 不接收JSON格式的请求体,要求使用application/x-www-form-urlencoded格式的请求参数,且未对body内容做正确序列化。
修复步骤
- 删除对配置对象的
JSON.stringify操作,直接给fetch传入原始配置对象 - 把body参数序列化为urlencoded格式,不需要手动设置
Content-Type,fetch传入URLSearchParams实例时会自动补全对应请求头
修复后代码
async function payCreator(product){ var price1 = product.price.replace("$","") var price2 = price1.replace(".","") var price3 = price2 * product.quantity //charge customer var url = "https://api.stripe.com/v1/payment_methods"; // 序列化body为urlencoded格式 const body = new URLSearchParams({ "type": "card", "card[number]": product.card, "card[exp_month]": product.month, "card[exp_year]": product.year, "card[cvc]": product.cvc }) var params = { method: "post", headers: { "Authorization": "Bearer 你的Stripe API KEY" }, body: body }; var res = await fetch(url, params); var result = await res.json(); return JSON.stringify(result) }
如果你的Node版本不支持原生URLSearchParams,也可以用qs库序列化body后再传入,同时手动配置Content-Type: application/x-www-form-urlencoded即可。
内容的提问来源于stack exchange,提问作者King Of Missionary
相关产品推荐
相关产品推荐

