[英]OpenWeather API, How do I pass in response from one response to another call?
[英]How can I check a fetch response to call another one?
我试图从API下载json文件。 为此,我需要调用3个端点。
http://url.com/export
它返回一个json: {"exportLoading":true,"file":"export-20190618-183316.json"}
之后,我应该调用第二个端点并检查此导出的状态:
http://url.com/export/status
它返回true
或false
(服务器正在处理时,此端点返回true
。返回false
,文件已完成下载。)
因此,如果status === false
,我可以调用最后一个端点http://url.com/download/file_name
(我通过第一个请求返回的文件名发出此请求,以下载文件。
我的问题是,如何检查第二个端点是否返回false
以发出最后一个请求并下载文件?
我一直做到第二个端点为止。
app.get('/export', function (req, res, next) {
global.fetch = fetch
global.Headers = fetch.Headers;
const headers = new Headers();
const username = 'user';
const password = 'pass';
const URL = 'http://url.com/export'
headers.set('Authorization', 'Basic ' + base64.encode(username + ":" + password));
fetch(URL, {
method: 'GET',
headers: headers,
})
.then(res => res.json())
.then(json => {
fetch("http://url.com/exportl/status", {
method: 'GET',
headers: headers,
}).then(result => ...)
})
.catch(function (error) {
console.log(error)
})
});
您可以使用while循环来调用端点,直到满足条件为止:
app.get('/export', async function(req, res, next) { global.fetch = fetch global.Headers = fetch.Headers; const headers = new Headers(); const username = 'user'; const password = 'pass'; const URL = 'http://url.com/export' headers.set('Authorization', 'Basic ' + base64.encode(username + ":" + password)); fetch(URL, { method: 'GET', headers: headers, }).then(r => r.json) .then(data => { // use data here var status = false while (!status) { status = await checkStatus() } // third call }) }); function checkStatus() { return fetch("http://url.com/exportl/status", { method: 'GET', headers: headers, }).then(r => r.json) }
注意,我不知道响应的状态,您将不得不更改代码以适应响应。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.