【发布时间】:2021-06-02 04:08:19
【问题描述】:
我正在向 YooKassa 的 api 发送post 请求以创建付款。我的请求适用于终端和 Postman 中的 curl。但是在使用axios 时,类似的请求在nodejs 中不起作用。以下两个例子:
Node.js:
/**
* Generate idempotence key if not present
* @see https://yookassa.ru/developers/using-api/basics#idempotence
*/
if (!idempotenceKey) idempotenceKey = uuid()
const uri = 'https://api.yookassa.ru/v3/payments'
const payload = {
amount: {
value: '2.50',
currency: 'RUB',
},
confirmation: { type: 'embedded' },
capture: true,
receipt: {
customer: {
email: 'test12@test.ru',
},
items: [
{
description: 'Album',
quantity: '1.00',
amount: { value: '2.00', currency: 'RUB' },
vat_code: '1',
},
],
},
save_payment_method: false,
description: 'Order №72',
}
try {
const { data } = await axios({
method: 'post',
url: uri,
data: payload,
auth: {
user: this.shopId,
pass: this.secretKey,
},
headers: {
'Content-Type': 'application/json',
'Idempotence-Key': idempotenceKey,
},
})
return data
} catch (error) {
return `Error: ${error}`
}
错误:
"Error: Error: Request failed with status code 401"
Curl 请求有效:
curl https://api.yookassa.ru/v3/payments \
-X POST \
-u user:pass \
-H 'Idempotence-Key: <Random uuid>' \
-H 'Content-Type: application/json' \
-d '{
"amount": {"value": "2.00", "currency": "RUB"},
"confirmation": {"type": "embedded"},
"capture": true,
"description": "Order №72",
"receipt": {
"customer": {
"email": "test12@test.ru"
},
"items": [
{
"description": "Album",
"quantity": "1.00",
"amount": {"value": "2.00","currency": "RUB"},
"vat_code": "1"
}
]
},
"save_payment_method": false
}'
或者建议我如何调试 401 错误。
问题中省略了用户名和密码。
谢谢!
【问题讨论】:
-
尝试检查错误响应标头,这些标头可能包含
WWW-Authenticate。要检查错误,您可以使用util.inspect而不仅仅是Error: ${error} -
@Aivaras 好的,如何转换普通视图?使用 return util.inspect(error) 后,我得到不可读的调试
-
util.inspect返回一个string。目前尚不清楚代码是否可以处理这个问题。查看该字符串的另一种方法是使用调试并添加断点或只是console.log -
状态码 401 是授权失败。您确定 shopId 和 secretKey 正确吗?