我是第一次问问问题的人,如果我在这个过程中犯了任何错误,我会提前道歉。感谢您提前的时间和帮助。
我的最终目标是使用Node / Express服务器访问Webdam.com API中的照片。 API文档提供了一个工作的CURL命令,我将其转换为我在浏览器中测试的jQuery.ajax()http调用。我希望将工作的jQuery.ajax()调用转换为Node / Express服务器上的代码,以保护我的API密钥。
最后,我希望使用Axios或Request的内容,但我可以选择其他选项。我已经在我的节点服务器上使用了jQuery,如here所述,但看起来这些代码示例已被弃用,因为jQuery需要一个window.document才能工作,在我看来Axios或Request会是更好的方式。
有关工作jQuery.ajax()http调用的一些背景信息,我首先检索Oauth2令牌。收到令牌后,我再次进行jQuery.ajax()调用以检索Webdam照片内容,API文档为here。
有人会帮助我将此jQuery.ajax()代码转换为Node / Express代码,以便我可以检索OAuth2令牌。
工作压力指令:
curl -X POST https://apiv2.webdamdb.com/oauth2/token -d 'grant_type=password&client_id=CLIENT_ID&client_secret=SECRET_KEY&username=USERNAME&password=USER_PASSWORD'
WORKING JQUERY.AJAX()CALL:
var params = {
grant_type: 'password',
client_id: CLIENT_ID,
client_secret: SECRET_KEY,
username: USERNAME,
password: USER_PASSWORD
};
$.ajax({
url: 'https://apiv2.webdamdb.com/oauth2/token',
type: 'POST',
dataType: 'json',
data: params,
success: function(response) {
return response.access_token;
},
error: function(error) {
return 'ERROR in webdamAuthenticate';
}
});

const axios = require('axios');
const params = {
grant_type: 'password',
client_id: CLIENT_ID,
client_secret: SECRET_KEY,
username: USERNAME,
password: USER_PASSWORD
};
axios.post('https://apiv2.webdamdb.com/oauth2/token/', params)
.then(response => {
console.log('success in axios webdamAuth', response);
})
.catch(err => {
console.log('ERROR in axios webdamAuth ');
});

这是我得到的错误响应,我以为我指的是grant_type,但它告诉我我不是。我用Google搜索了错误,但不明白我错过了什么,请帮助。
{ error: 'invalid_request',
error_description: 'The grant type was not specified in the request' }
400
{ date: 'Mon, 04 Dec 2017 19:19:34 GMT',
server: 'Apache',
'strict-transport-security': 'max-age=86400; includeSubDomains',
'access-control-allow-origin': '*',
'access-control-allow-headers': 'Authorization, X-XSRF-TOKEN',
'access-control-allow-methods': 'POST, GET, OPTIONS, DELETE, PUT',
'cache-control': 'private, no-cache, no-store, proxy-revalidate, no-transform, max-age=0, must-revalidate',
pragma: 'no-cache',
'content-length': '97',
connection: 'close',
'content-type': 'application/json'}

答案 0 :(得分:0)
从你工作的curl命令,它以默认格式POST
发送application/x-www-form-urlencoded
数据。要对表单进行编码,请在axios中对数据进行网址编码,您可以参考this。
例如:
const axios = require('axios');
const querystring = require('querystring');
var params = {
grant_type: 'password',
client_id: CLIENT_ID,
client_secret: SECRET_KEY,
username: USERNAME,
password: USER_PASSWORD
};
axios.post(
'https://apiv2.webdamdb.com/oauth2/token',
querystring.stringify(params), {
headers: {
'User-Agent': 'YourApp'
}
});