【问题标题】:NodeJs not attatching both filter properties to url paramsNodeJs 没有将两个过滤器属性都附加到 url 参数
【发布时间】:2021-02-25 07:28:18
【问题描述】:

我正在尝试执行获取请求并将几个 url 参数传递到请求中,但由于某种原因,该请求似乎只是添加了两个具有相同名称的 url 参数之一。

我的代码是:

  async function getOrderByDate(data) {
   const options = {
    method: 'get',
    url: config.cloverApiUrl +'/v3/merchants/'+data.merchant_id
      +'/orders',
    headers: {
      Authorization: 'Bearer ' + data.token,
      ContentType: 'application/json'
    },
    qs: {
      filter: `clientCreatedTime>` +data.minDate,
      filter: `clientCreatedTime<` +data.maxDate,
      expand: 'lineItems',
      limit: 1000
    }
  };
  console.log('here ' +JSON.stringify(options.qs));
  const response = request(options);
}

问题是当我在收到请求之前记录查询参数时:

 here {"filter":"clientCreatedTime<1613624400000","expand":"lineItems","limit":1000}

我不知道为什么它只添加了所有 url 参数,包括一个 clientCreatedTime 过滤器而不是另一个。提前感谢您的帮助。

【问题讨论】:

  • 对象属性唯一,filter只能有一个。
  • 但是在三叶草的文档中,他们说要通过多个过滤器进行多次过滤,并且在邮递员中也可以正常工作。有没有办法解决?由于不允许对象上的重复属性,那么将多个相同的 url 参数传递到请求中的替代方法是什么?
  • 你能链接文档吗?
  • 三叶草过滤器的文档是:docs.clover.com/docs/applying-filters

标签: javascript node.js request query-parameters


【解决方案1】:

你必须使用一个数组:

      filter: [`clientCreatedTime>` +data.minDate, `clientCreatedTime<` +data.maxDate],

您必须将qsStringifyOptions 设置为{ indices: false }

   const options = {
    method: 'get',
    url: config.cloverApiUrl +'/v3/merchants/'+data.merchant_id
      +'/orders',
    headers: {
      Authorization: 'Bearer ' + data.token,
      ContentType: 'application/json'
    },
    qs: {
      filter: [`clientCreatedTime>` +data.minDate, `clientCreatedTime<` +data.maxDate],
      expand: 'lineItems',
      limit: 1000
    },
    qsStringifyOptions: { indices: false }
  };

另外,request 已被弃用。因此,您很可能想找到一种处理fetch 的方法。为此存在几个包,例如node-fetchwhatwg-fetchisomorphic-fetch

另外提醒一下,如果是 request 库,您需要使用回调或将其视为流。如果是request-promise,那会给你一个承诺,但你确实需要await 才能得到响应。 async 函数没有返回值。

【讨论】:

  • 感谢您的回答,它就像一个魅力。我知道不推荐使用的请求,并计划更改 api 以使用新包。目前我正在使用 request-promise,您会推荐哪个作为 request-promise 的最佳替代方案,并且易于切换?
  • 我使用node-fetch。它模仿浏览器获取 API。 MDN
猜你喜欢
  • 2011-05-29
  • 2019-10-05
  • 2019-07-09
  • 2021-07-03
  • 2015-10-06
  • 1970-01-01
  • 2015-04-22
  • 1970-01-01
  • 2023-03-11
相关资源
最近更新 更多