[英]How to Convert This Curl Request to Javascript
我正在使用Streamlabs API更新用戶的忠誠度積分。 執行以下操作后,點不會更新,並且會向catch塊引發錯誤。 為此請求給出的唯一示例是curl請求。 (請參閱此處 )。 也許他們的榜樣是錯誤的?
我正在使用Javascript和Request-Promise模塊。 我已經成功地使用Twitch使用此模塊為Oauth完成了POST請求。 但是,我無法將此帖子發布到Streamlabs API上,我嘗試了幾種方法。 這是我用於Twitch API的POST請求的相同代碼,並且成功。 我無法弄清楚為什么它不適用於Streamlabs:
const options = {
access_token: streamlabsToken,
channel: TWITCH_CHANNEL,
users: 'users[' + username + ']=' + REFERRAL_POINTS
}
request.post(pointsAddEndpoint, { json: options })
.then((slResponse) => { // Then 2
if (slResponse.hasOwnProperty('message')) {
console.log('Streamlabs response: ' + slResponse.message);
}
res.end();
})
.catch(function (error) {
console.log('Error adding refer points: ' + error.message);
res.end();
});
我確定我只是在這里格式化錯誤的內容,有輸入嗎?
UPDATE
我接到要求去上班的請求。 “用戶”的參數不應為“用戶=用戶[用戶名] = 20&用戶[用戶名] = 30”,而應僅為“用戶[用戶名] = 20&用戶[用戶名] = 30”(已刪除“用戶=”) 。
我是這樣在我的options
對象中做到的:
const options = {
access_token: streamlabsToken,
channel: TWITCH_CHANNEL
}
options['users[' + username + ']'] = REFERRAL_POINTS;
但是,這仍然行不通。 我知道我正確設置了“用戶”參數,因為我打印了日志options['users[' + username + ']']
,它給了我正確的REFERRAL_POINTS。
在這一點上,我正在考慮將整個內容輸入為字符串。 如何將其傳遞到request.post
的正文中?
const options = {
method: 'POST',
uri: 'https://streamlabs.com/api/v1.0/points/add', // whatever the endpoint
body: {
access_token: streamlabsToken,
channel: TWITCH_CHANNEL,
users: 'users[' + username + ']=' + REFERRAL_POINTS
},
json: true // Automatically stringifies the body to JSON
};
request(options)
.then((parsedBody) => {
// POST succeeded...
})
.catch((err) => {
// POST failed...
});
因此,即使API參考說明您應該這樣做,該API仍不接受主體參數。 實際上,它們應該是查詢參數。 我猜API參考不正確。 我將參數直接添加到url中,並將Streamlabs OAuth訪問令牌放在標題中,然后它起作用了!
var dataString = 'users[' + username + ']=' + REFERRAL_POINTS + '&channel=' + TWITCH_CHANNEL;
const options = {
method: 'POST',
url: 'https://streamlabs.com/api/v1.0/points/add' + '?' + dataString,
headers: {
'Authorization': 'Bearer ' + streamlabsToken
},
json: true
};
request.post(options)
.then((slResponse) => {
// Do something
})
.catch(function (error) {
// Do something
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.