【问题标题】:get endpoint on nodejs produces no output在nodejs上获取端点不产生输出
【发布时间】:2018-04-09 19:24:43
【问题描述】:

我在 nodejs 上有一个端点,尽管它是一个承诺,但它不会产生任何输出,它应该返回输出。这是我的要求:

TegucigalpaData: () => {
        let url = `https://maps.googleapis.com/maps/api/geocode/json?address=${encodeURIComponent('Tegucigalpa, Honduras')}`;
        axios.get(url).then( (response) => {
            if(response.data.status === 'ZERO_RESULTS') {
                throw new Error(`Unable to find the address: ${address}`);
            }
            let lat = response.data.results[0].geometry.location.lat;
            let lng = response.data.results[0].geometry.location.lng;
            let wurl = `https://api.darksky.net/forecast/dc6c0d767d55ffe8f172d4c187852db8/${lat},${lng}?lang=es&units=si`;
            return axios.get(wurl);
        }).then( (response) => {
            let temperature = response.data.currently.temperature;
            let apparentTemperature = response.data.currently.apparentTemperature;
            return { temp: temperature, appTemp: apparentTemperature }
        }).catch( (error) => {
            return "Unable to connect to the API servers";
        });
    } 

然后,在我的端点上:

app.get('/weatherData', (req, res) => {
    let data = TegucigalpaData();
    res.send(data);
});

但是,我没有得到任何 json 格式的数据输出。知道我可能做错了什么吗?

【问题讨论】:

  • 你的 TegucigalpaData() 函数是异步的 你在 TegucigalpaData 函数完成之前调用 res.send(data) 发生了什么。
  • @csaiki 我该如何解决这个问题?

标签: node.js express


【解决方案1】:

尝试直接在处理程序中发送结果:

app.get('/weatherData', (req, res) => {
    let url = `https://maps.googleapis.com/maps/api/geocode/json?address=${encodeURIComponent('Tegucigalpa, Honduras')}`;
    axios.get(url).then( (response) => {
        if(response.data.status === 'ZERO_RESULTS') {
            throw new Error(`Unable to find the address: ${address}`);
        }
        let lat = response.data.results[0].geometry.location.lat;
        let lng = response.data.results[0].geometry.location.lng;
        let wurl = `https://api.darksky.net/forecast/dc6c0d767d55ffe8f172d4c187852db8/${lat},${lng}?lang=es&units=si`;
        return axios.get(wurl);
    }).then( (response) => {
        let temperature = response.data.currently.temperature;
        let apparentTemperature = response.data.currently.apparentTemperature;
        return res.send({ temp: temperature, appTemp: 
        apparentTemperature })
    }).catch( (error) => {
        return res.send(error)
    });
} 
});

【讨论】:

  • 第一个场景会引发错误:TypeError: Cannot read property 'then' of undefined 其中 undefined 是 promise 变量。
  • @codeninja 尝试直接发送响应(参见编辑后的答案)
猜你喜欢
  • 2021-06-28
  • 2018-12-11
  • 2012-01-07
  • 2017-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-07
  • 1970-01-01
相关资源
最近更新 更多