Skip to content

node Fetch return undefined body from API

I’m learning Javascript and Node.js.

I am trying to return the body of the response by using node-fetch but I received an undefined output.

Is there any way that I can get the body returned?

const express = require('express')
const router = express.Router()
const fetch = require('node-fetch');

router.get('/', (req, res) =>{

    let zipcode = req.query.zipcode;

    let temp = getGeoCode(zipcode);
    
    console.log(temp); 

**//here returns promise<pending>**

    temp.then(function(result){

        console.log(result); 

**//here returns undefined**
    })

 async function getGeoCode(zipcode){

   await fetch(`https://public.opendatasoft.com/api/records/1.0/search/?dataset=us-zip-code-latitude-and-longitude&q=${zipcode}&facet=state&facet=timezone&facet=dst&refine.state=MA`)
    .then(
        res =>res.json()
        )
    .then(json => {
        res.send(`The lon and lat in your zipcode "${zipcode}" - ${json.records[0].fields.city}, ${json.records[0].fields.state} is ${json.records[0].fields.longitude}, ${json.records[0].fields.latitude}.`) 

**//Here works well!!!**
        
    })
    .catch(error =>{
        console.log(error)
    })

 }

})

Answer

It’s as simple as that when you stop messing with your head with the .then() Promise-style, and you use only the async/await style :

router.get('/', async (req, res) => {
    let zipcode = req.query.zipcode;
    const response = await fetch(`....`);
    const result = await response.json();
    console.log(result);
    res.send(`The lon and lat.....`)
})