【问题标题】:How to pass parameters in empty object to get valid url如何在空对象中传递参数以获取有效的 url
【发布时间】:2017-11-11 11:03:02
【问题描述】:

如何在空对象中传递参数以获得有效的url?

我正在使用 fetch 方法来获取 API 和获取 url,但需要设置查询参数才能获取完成的 url。

我需要将 stationIddate 传递给 params 并在 fetchtrips 函数中设置,现在它只得到类型为“到达”。

 export default class Api {
  static fetch(type, params = {}) {
    const url = `${config.api.host}${config.api.paths[type]}`;
    console.log(url)
    let options = {
      headers: config.api.headers
    };

    Object.assign(options, params);

    return fetch(url, options)
      .then(response => response.json())
      .catch(error => Promise.reject(error));
  }
  static fetchTrips(stationId, date) {
    const apiURL = Api.fetch('arrivals');
    return apiURL;
  }
}

【问题讨论】:

  • 在我看来你可以做到Api.fetch('arrivals',{'stationId':stationId, 'date':date })

标签: javascript parameter-passing query-string fetch


【解决方案1】:

尝试查询字符串节点模块来创建查询参数。

从“查询字符串”导入查询字符串;

static fetch(type, params = {}) {
   const queryParam = queryString.stringify(param);
   const url = `${config.api.host}${config.api.paths[type]}${queryParam}`;
   let options = {
       headers: config.api.headers
   };
   return fetch(url, options)
       .then(response => response.json())
       .catch(error => Promise.reject(error));
}

【讨论】:

    猜你喜欢
    • 2012-10-09
    • 2019-10-28
    • 2021-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-09
    • 1970-01-01
    • 2018-07-05
    相关资源
    最近更新 更多