我正在尝试使用request-promise在nodejs中复制以下CURL请求(最终,我需要使用promises,所以我更喜欢这种方法):
curl -H "Authorization: Token token=[API Key]" -H "Accept: application/vnd.moonclerk+json;version=1" https://api.moonclerk.com/customers
以下代码段显示了我的尝试:
var rp = require('request-promise');
var querystring = require('querystring');
//this is what I think is causing me trouble
var bodyHeaders = querystring.stringify({
"Authorization": "Token token=[token taken out in code snippet]",
"Accept": "application/vnd.moonclerk+json;version=1"
});
var options = {
uri: 'https://api.moonclerk.com/customers',
method: 'GET',
body: bodyHeaders
};
var cb = function () {
return function (response) {
console.log("response: ", response);//this should spit out the JSON text I'm looking for
}
}
rp(options).then(cb())
但我在nodejs控制台中获取Possibly unhandled StatusCodeError: 401 - HTTP Token: Access denied.
作为响应。这有什么问题?
PS - 请注意,我的uri是HTTPS(即'https://api.moonclerk.com/customers');这是导致问题的原因吗?
答案 0 :(得分:1)
您无法在请求正文中传递HTTP标头,服务器无法识别它们。有关请求库的正确用法,请参阅https://github.com/request/request#custom-http-headers。
var options = {
// ...
headers: {
"Authorization": "Token token=[token taken out in code snippet]",
"Accept": "application/vnd.moonclerk+json;version=1"
}
});