在获取请求

时间:2018-02-22 06:52:43

标签: node.js express requestjs

router.get('/getpostcode', function(req, res){
    console.log(req.query.suburb);

    var options = {
        url: 'http://apiurl?suburb=' + req.query.suburb + "&state=" + req.query.state ,
        headers: {
            'auth-key': key
        }
    }

    request(options, callback);

    function callback(error, response, body){
        if(!error && response.statusCode == 200){
            info = JSON.parse(body);
            info = info.localities.locality;
            if( Object.prototype.toString.call( info ) == '[object Array]' ){

                for ( var x = 0 ; x < info.length ; x++ ){
                    var locx = info[x].location;
                    var qsuburb = req.query.suburb;

                    if( locx == qsuburb.toUpperCase() ){
                        res.send( { 'postcode': info[x].postcode } );
                    }
                }

            } else if (Object.prototype.toString.call( info ) != '[object Array]') {

                var locx = info.location;
                var qsuburb = req.query.suburb;
                if ( locx == qsuburb.toUpperCase() ){
                    res.send( { 'postcode': info.postcode } );
                }
            }            
        }
    }
});

所以,我试图从API请求数据,然后根据该数据,然后我发回一些数据。我的代码如上所述。

不幸的是,在回调函数中,当我运行一个循环来查找我将发送回客户端的特定元素时,在将该元素发送到客户端时,我收到错误,如标题所示。< / p>

当没有循环时我不会发生这种情况,我只是将数据的一个元素发回。

关于这可能是什么的任何想法?

3 个答案:

答案 0 :(得分:1)

您在流程中至少两次到达res.send函数调用,这是不允许的。必须调用该函数一次才能将响应发送给客户端。

答案 1 :(得分:1)

您正在为一个请求发送多个响应,在循环外写入res.send或JSON。

for (var x = 0; x < info.length; x++) {
    var locx = info[x].location;
    var qsuburb = req.query.suburb;
    var postcodes = [];
    if (locx == qsuburb.toUpperCase()) {
        postcodes.push({
            'postcode': info[x].postcode
        });
    }
    res.json(postcodes);
}

答案 2 :(得分:0)

是的,正如@Rahul所说,不允许为同一个请求多次发送回复 - 您必须获得相同的邮政编码,因此您需要将邮政编码存储在变量中并发送循环结束后,您可以使用break。虽然不建议在非常简单的循环中使用复杂循环中断,但可以利用它的用法。

for (var x = 0; x < info.length; x++) {
    var locx = info[x].location;
    var qsuburb = req.query.suburb;

    if (locx == qsuburb.toUpperCase()) {
        res.send({
            'postcode': info[x].postcode
        });
        break;
    }
}

或者如下:

for (var x = 0; x < info.length; x++) {
    var locx = info[x].location;
    var qsuburb = req.query.suburb;
    vat postcode = = null;
    if (locx == qsuburb.toUpperCase()) {
        postcode = info[x].postcode
    }
}
res.send({
    postcode
});