我正在嘗試向 Stripe 發送一個 JSON 物件,但我總是收到來自回應的錯誤。
API 已決議,但未發送對 /api/ctrlpnl/products_submit 的回應,這可能會導致請求停滯。{ 錯誤:{ 代碼:'parameter_unknown',doc_url:'https://stripe.com/docs/error-codes/parameter-unknown',訊息:'收到未知引數:{"name":"dasdas"}',引數:'{"name":"dasdas"}',型別:'invalid_request_error' } }
我的代碼如下:
import Stripe from 'stripe';
import { NextApiRequest, NextApiResponse } from 'next';
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY, {
apiVersion: '2020-08-27'
});
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method === 'POST') {
try {
const name = { name: req.body.name };
fetch(`${process.env.BASE_URL}/v1/products`, {
method: 'POST',
body: JSON.stringify(name),
headers: {
'Accept': 'application/json',
"content-type": 'application/x-www-form-urlencoded',
Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,
}
}).then((response) => {
return response.json();
}).then(data => {
console.log(data);
res.status(200).json(data)
})
} catch (err) {
res.status(err.statusCode || 500).json(err.message);
}
} else {
res.setHeader('Allow', 'POST');
res.status(405).end('Method Not Allowed');
}
}
uj5u.com熱心網友回復:
該content-type的fetch正確設定為application/x-www-form-urlencoded,但body包含了JSON。所以 Stripe 無法決議body引數。
要解決這個問題,您需要替換JSON.stringify為new URLSearchParams:
const name = { name: req.body.name };
fetch(`${process.env.BASE_URL}/v1/products`, {
method: 'POST',
body: new URLSearchParams(name), // ← this will return "name=xxxx"
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': `Bearer ${process.env.STRIPE_SECRET_KEY}`,
}
});
請注意,我建議使用Stripe 庫,它使用起來要簡單得多:stripe.products.create(name);,特別是因為您已經將它包含在您的代碼中。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/374241.html
