Monday, 5 June 2017

express routing triggers: "Can't set headers after they are sent." error

I am new to Express, and having trouble sending data from backend to front end. Here is what I want to do: I have a Google Map API on the homepage (home.ejs). app.js is the server code: when the page is loaded, app.js generate some random locations and send to home.ejs, so home.ejs use those locations as Markers. Now I want to add event listeners to each of these markers, so that when mouse is over it, it send a GET request to server, and request a picture to display.

I feel it a big challenge for me to send the request/data back and forth. When the mouse is over, the home.ejs sends a GET Request to /getImge/:num route, and app.js responds to that request by retrieving the image url, and redirect to "/" and sends the url to it. This is where I get the "Can't set headers after they are sent".

I am so new to Express and ejs that I don't even know if I am on the right track. How should I implement this to get the communication through?

This is the app.js server file

var express = require("express");
var app = express();
//app.use(express.static(__dirname + "/public"));
app.use(express.static(__dirname));
app.set("view engine","ejs");

var lng_min = -84.161;
var lng_max = -83.688; 
var lat_min = 35.849;
var lat_max = 36.067;

var urls = [
    "http://cdn1-www.dogtime.com/assets/uploads/2015/01/file_21032_the-most-popular-dog-and-cat-names.jpg",
    "http://qltyctrl.com/wp-content/uploads/2014/03/Sad-Dog-and-Cat.jpg",
    "https://blog-photos.dogvacay.com/blog/wp-content/uploads/2015/07/dog-cat-smarter-ftr.jpg",
    "http://qltyctrl.com/wp-content/uploads/2014/03/Dog-and-Cat-on-a-Log.jpg",
    "http://images.boomsbeat.com/data/images/full/31730/cat-and-dog_1-jpg.jpg",
    "http://www.vetlocator.com/dailypaws/wp-content/uploads/2012/04/dog-cat2.jpg",
    "http://qltyctrl.com/wp-content/uploads/2014/03/Old-Dog-and-Cat-Sleepy-Embrace.jpg",
    "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQXNMdvNfc3WYMqbPrJrnjgHJRp2zB1y9vx545LfO-_U5_yvgBo",
    "http://www.vetlocator.com/dailypaws/wp-content/uploads/2012/04/dog-cat8.jpg",
    "http://www.maddiesfund.org/assets/metaImage/robust-dog-cat-foster.jpg"
]

var numLocations = 10;
var data = []; 

function generateData() {
    // generate random locations and the url to download pictures
    for (var i = 0; i < numLocations; ++i) {
        var lng = Math.random() * (lng_max - lng_min) + lng_min;
        var lat = Math.random() * (lat_max - lat_min) + lat_min;
        var tuple = {
            id: i,
            lng: lng,
            lat: lat,
            pic: urls[i]
        };
        data.push(tuple);
    }
}

app.get("/", function(req, res) {
    //res.send("Hello it works");
    data = [];
    generateData();
    res.render("home.ejs", {data: data});
});

app.get("/getImg/:num", function(req, res) {
  console.log(req.params.num);
  var i = Number(req.params.num);
  res.redirect("/");
  res.send({imgUrl: data[i].pic});
});


app.listen(process.env.PORT, process.env.IP, function() {
   console.log("Server Started!"); 
});

home.ejs file:

<!DOCTYPE html>
<html>
<head>
    <title>Demo</title>
    <link rel="stylesheet" type="text/css" href="/public/app.css">

</head>
<body>
    <div id="map">
    </div>

    <script>
      var data = <%- JSON.stringify(data) %>;
      console.log(data.length);
      function initMap() {
        var loc = {lat: 35.9606, lng: -83.9207};
        var map = new google.maps.Map(document.getElementById('map'), {
          zoom: 10,
          center: loc
        });
        for (var i = 0; i < data.length; ++i) { 
            var loc = {lat: data[i].lat, lng: data[i].lng}; 
            var marker = new google.maps.Marker({
                  position: loc,
                  map: map
                  // id: i
            }); 

            var infowindow = new google.maps.InfoWindow();
            google.maps.event.addListener(marker, 'mouseover', (function(marker) {
            return function() {
                  // var content = '<div id="imgDisplay">'
                  //                   + '<img src="http://www.maddiesfund.org/assets/metaImage/robust-dog-cat-foster.jpg">'  
                  //                 + '</div>';
                  // infowindow.setContent(content);
                  // infowindow.open(map, marker);


              var xhr = new XMLHttpRequest();
              var params = 3;
              xhr.open('GET','/getImg/'+params, true);
                  xhr.onreadystatechange = function() {
                    if (xhr.readyState == 4 && xhr.status == 200) {
                      console.log(responseText);
                }
                  }
            //xhr.send(params);
            xhr.send();


            }
         })(marker));


         }
      }
    </script>

    <script async defer
    src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAOwfkV_GbUXyH2s8iD0gS6pje9J3R96dM&callback=initMap">
    </script>

</body>
</html>



via daydayup

No comments:

Post a Comment