在发出HTTP请求时不会触发回调

时间:2018-03-20 12:01:01

标签: javascript node.js callback

我正在尝试通过使用以下网址向Google API提供地址来获取纬度和经度作为输出:https://maps.googleapis.com/maps/api/geocode/json?address=${encodedAddress}.

延迟5分钟后执行回调并打印: 'Unable to connect to the Google service'.

我尝试在带有自定义地址的Chrome浏览器中运行上面提到的网址,并且通过提供JSON输出它可以正常工作,但它似乎不适用于我的应用。这是代码,任何帮助将不胜感激:

const request = require('request');
var geocodeAddress = (address, callback) => {

var encodedAddress = encodeURIComponent(address);
console.log(encodedAddress);

request({
    url: `https://maps.googleapis.com/maps/api/geocode/json?address=${encodedAddress}`,
    json: true
}, (error,response,body) => {

    if (body.status === 'OK'){

        callback(undefined, {
            address: body.results[0].formatted_address,
            latitude: body.results[0].geometry.location.lat,
            longitute: body.results[0].geometry.location.lng
        });

    } else if (body.status === 'ZERO_RESULTS') {
        callback('Unable to find that address');
    } else if (error) {
        callback('Unable to connect to google service');
    } 
});

}

module.exports.geocodeAddress = geocodeAddress;

1 个答案:

答案 0 :(得分:0)

永远不会调用回调,因为只有处理3个状态才有更多。做一个简单的请求我得到body.status === 'OVER_QUERY_LIMIT'没有错误。

const request = require('request');
var geocodeAddress = (address, callback) => {

    var encodedAddress = encodeURIComponent(address);
    console.log(encodedAddress);

    request({
        url: `https://maps.googleapis.com/maps/api/geocode/json?address=${encodedAddress}`,
        json: true
    }, (error, response, body) => {

        if (error) {
            callback('Unable to connect to google service');
            return;
        }

        if (body) {

            if (body.status === 'OK') {

                callback(undefined, {
                    address: body.results[0].formatted_address,
                    latitude: body.results[0].geometry.location.lat,
                    longitute: body.results[0].geometry.location.lng
                });

            } else if (body.status === 'ZERO_RESULTS') {

                callback('Unable to find that address');

            } else {
                //handle all the rest here
                console.log(body.status);
                callback(body.status);
            }

        } else {
            //handle all the rest here
            console.log("No body");
            callback("No body");
        }

    });

}

module.exports.geocodeAddress

= geocodeAddress;