使用另一个fetch从fetch内部更改json对象属性



我正在使用REST国家API创建一个web应用程序(提供链接(https://restcountries.com/.
neneneba API提供json,属性为borders,这是一个字符串数组,用于提供边界国家的cca3。我也想知道这些国家的名字,所以我再次要求提供这些数据。到目前为止,这就是我所想到的。但是,从第一个请求返回的json从未更改。我不知道发生了什么事,如果有人能给我建议的话?

const dataAPI = 'https://restcountries.com/v3.1/'
router.get('/country/:code', (req, res, next) => {
const code = req.params.code
fetch(`${dataAPI}/alpha/${code}?fields=borders`)
.then(response => response.json())
.then(json => fetch(`${dataAPI}/alpha?codes=${json.borders.join()}&fields=cca3,name`))
.then(response => response.json())
.then(bordersJson => {
fetch(`${dataAPI}/alpha/${code}`)
.then(response => response.json())
.then(data => {
data.borders = bordersJson
res.send(data)
}).catch(err => next(err))
}).catch(err => next(err))
})
对于这种情况,

Async/await是一种更好的方法。

const dataAPI = 'https://restcountries.com/v3.1/'
router.get('/country/:code', async (req, res, next) => {
try {
const code = req.params.code;
const borderJSON = await fetch(`${dataAPI}/alpha/${code}?fields=borders`).then(response => response.json());
// response:  {"borders":["BGD","BTN","MMR","CHN","NPL","PAK"]}
const codes = borderJSON.borders.join(',');
const cca3 = await fetch(`${dataAPI}/alpha?codes=${codes}&fields=cca3,name`)).then(response => response.json());
//  [{"name":{...},"cca3":"BGD"},{"name":{...},"cca3":"PAK"}]
res.send(cca3);
} catch (err) {
next(err);
}

});

borders属性未被替换的原因是所使用的API端点返回一个带有一个对象的数组,而不是对象本身。此外,我发现没有必要单独寻找边界。

最终解决方案

router.get('/country/:code', (req, res, next) => {
const code = req.params.code
fetch(`${dataAPI}/alpha/${code}`)
.then(response => response.json())
.then(json => {
json = json[0]
fetch(`${dataAPI}/alpha?codes=${json.borders.join()}&fields=cca3,name`)
.then(response => response.json())
.then(bordersJSON => {
json.borders = bordersJSON
res.send(json)
}).catch(err => next(err))
}).catch(err => next(err))
})

最新更新