2017-11-11 192 views
0

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

我使用fetch方法来创建API并获取url,但需要设置查询参数才能获得完成的url。

我需要通过的stationID & 日期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; 
    } 
} 
+0

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

回答

0

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

从“query-string”导入queryString;

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)); 
}