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

228
Visualizações
Not getting desired response from api call in express and node.js

This question arouse while working with these technologies- React.js | Node.js | Express.js | MongoDB

I developed an API endpoint api/events/allevents as following-

router.get('/allevents', async (req, res) => {
    let success = false;
    try{
        const allevents = await Event.find({});
        success = true;
        res.json({success, allevents});
    }
    catch(err){
        res.status(400).json({ success: success, error: "no events found" });
    }
})

And I tested it in Thunder Client in VS Code and everything is perfect with the following response-

{
  "success": true,
  "allevents": [
    {
      "_id": "62d021d273b4565d056574ac",
      "title": "The Summer Night",
      "description": "The Summer Night is a musical night in which singers and bands will perform live.",
      "address": "New Delhi Auditorium",
      "city": "New Delhi",
      "state": "New Delhi",
      "country": "India",
      "days": 1,
      "date": "30/7/2022"
    }
  ]
}

Then after it I was trying to call it by the following function in a React.js component as following-

        async function fetchAllEvents() {
            const response = await fetch('/api/events/allevents', {
                method: 'get',
            }
            );
            console.log(response);
            let json = await response.json();
            console.log(json);
        }
        fetchAllEvents();

And in Edge browser's console, this is the response-

enter image description here

Why I am not getting the expected response same as above in Thunder Client's case ? I know I am very close to get the correct response, but I am not getting what is that little error . Can you help me with that ? Also it would be a great help if someone explains in detail how the api endpoint definition and api call are communicating to each other.

Kindly ignore the mistakes as it is from a beginner's side :)

about 4 years ago · Santiago Gelvez
1 Respostas
Responde à pergunta

0

Unexpected token < means response is HTML instead of JSON, Reason could be other thing than code shared over here. You can easily identify it by looking console of browser devtool console / network tab. By looking at code here, change you should make are,

send response as jsonp ( much convenient on transport then json )

router.get('/allevents', async (req, res) => {
    let success = false;
    try{
        const allevents = await Event.find({});
        success = true;
        res.jsonp({success, allevents});
    }
    catch(err){
        res.status(400).json({ success: success, error: "no events found" });
    }
})



async function fetchAllEvents() {
            try {
            const response = await fetch('/api/events/allevents', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json'
                  }
            }
            );
            console.log(response);
            let json = await response.json();
            console.log(json);
            }
         catch(error) {
           console.error(error)
          }  
        }
        fetchAllEvents();
about 4 years ago · Santiago Gelvez 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