如何将有效的 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 密钥。

最后我希望使用类似于 Axios or Request but I'm open to other options. I've looked into using jQuery on my Node server as is mentioned 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'

正在工作 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 但它告诉我我不是。我用谷歌搜索了这个错误,但不明白我遗漏了什么,请帮忙。

{ 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-urlencodedPOST 数据。要编码您的表单 url-在 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'
        }
});