node.jsexpressrequestjs

Can't set headers after they are sent in get request


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 } );
                }
            }            
        }
    }
});

So, I am trying to request data from an API and then based on that data, I am then sending some data back. My code is as above.

Unfortunately, in the callback function, when I am running a loop to find a specific element that I will then send back to the client, when sending that element to client, I am getting the error as shown in the title.

This does not occur when there is no loop and I simply send one element of the data back.

Any ideas on what this could be?


Solution

  • You are sending response more than one for one request, write res.send or JSON outside the loop.

    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);
    }