繁体   English   中英

如何将有效的curl / jquery.ajax调用转换为Node / Express中的后端

[英]How to convert a working curl/jquery.ajax call onto the backend in Node/Express

我是第一次问这个问题,如果我在此过程中有任何错误,请先道歉。 感谢您的时间和事先的帮助。

我的最终目标是使用Node / Express服务器从Webdam.com API访问照片。 API文档提供了一个有效的CURL命令,我将其转换为我在浏览器中测试过的jQuery.ajax()http调用。 我希望将工作的jQuery.ajax()调用转换为Node / Express服务器上的代码,以保护我的API密钥。

最后,我希望使用与AxiosRequest类似的东西,但我愿意接受其他选择。 我已经研究过在这里提到的 Node服务器上使用jQuery的方法,但是这些代码示例似乎已被弃用,并且由于jQuery需要window.document起作用,因此在我看来Axios或Request会是更好的选择。

有关正在运行的jQuery.ajax()http调用的一些背景信息,我首先获取一个Oauth2令牌。 收到令牌后,我再次调用jQuery.ajax()来检索Webdam照片内容,API文档在此处

有人会协助我将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'

工作JQUERY.AJAX()呼叫:

  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'; } }); 
AXIOS尝试不起作用:

 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'} 

通过您的curl命令,它以默认格式application/x-www-form-urlencoded发送POST数据。 要在axios中对表单进行url-encode编码,可以参考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'
        }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM