我尝试从 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)
}
Note, I do not know the response from the status, you will have to change the code to accommodate the response.
关于javascript - 如何检查获取响应以调用另一个获取响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56665383/