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

270
Visualizações
Variable out of scope (probably) - undefined

So this piece of code is returning description of word in json from https://sjp.pl/ webiste, word which user provied before in request json body

And problem is that i want to send back var 'desc' in res.send but its undefined. How I can access that and send it?

I think thats because item.push($(this).text()) is working only in this axios function and can be accessed only in this scope


const item = [];
var desc;

app.post('/test', (req, res) => {
    const { word } = req.body;

    if(!word) {
        res.status(418).send({error: 'no word provided'})
    }

    console.log(word)

    axios(`https://sjp.pl/${word}`).then(res => {

        const html = res.data
        const $ = cheerio.load(html)

        $('p').each(function() {
            item.push($(this).text())
        })

        desc = item[3]

        console.log(desc) // working until here
    })

    console.log(desc) // undefined here

    res.send({
        description: `${desc}`
    })
})
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Use res inside the axios like below. You are getting undefined because the desc scope ends inside that anonymous function. Moreover the axios is async. You may need to use await to make it sync or can follow the idea I proposed below.

const item = [];
var desc;

app.post('/test', (req, res0) => {
    const { word } = req.body;

    if(!word) {
        res0.status(418).send({error: 'no word provided'})
    }

    console.log(word)

    axios(`https://sjp.pl/${word}`).then(res => {

        const html = res.data
        const $ = cheerio.load(html)

        $('p').each(function() {
            item.push($(this).text())
        })

        desc = item[3]

        res0.send({
            description: `${desc}`
        })
    })
})
about 4 years ago · Juan Pablo Isaza 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