Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

154
Visualizações
Changing json object property from inside fetch using another fetch

I am creating a web application using the REST Countries API (link given) https://restcountries.com/.
The API gives json with the property borders, which is an array of strings giving the cca3 of the bordering countries. I would like to get the names of the countries too and so am making another request for that data. So far this is what I have come up with. But, the json returned from the first request is never changed. I don't know what is going on, if anybody could advice?

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))
})
over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

Async/await is a better approach for this case.

  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);
        }
    
    });
over 4 years ago · Santiago Trujillo Relatório

0

The reason the borders property was not replaced was that the API endpoint used returns an array with one object, not the object itself. Also, I found that finding the borders separately was unnecessary.

Final Solution

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))
})
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda