Wednesday, 10 May 2017

Node.js http GET request Syntax error in JSON

I've searched a lot, but cannot find the answer to my situation.

This is my server side code.

router.get("/user/detail/:id", function (req, res) {
  var id = req.params.id;
  http.get({
    host: server.host,
    port: server.port,
    path: '/db/user/' + id
  }, function (response) {
        var user = '';
        response.on('data', function (data) {
            user += data;
        });
        response.on('end', function () {
          var parsed = JSON.parse(user);
          console.log(parsed);
          res.render("pages/demo", {user : req.session.user, userProfile : parsed});
        });
        response.on('error', function (err) {
          console.log("in response error")
          console.log(err);
          throw err;
        });
  });
});

HTML script code for listening to click event

  $(".btnDetail").on("click", function() {
    var userId = $(this).attr("tag");
    console.log(userId);
    var url = "/admin/user/detail/" + userId;
    console.log(url);
    window.location.href = url;
  });

I am able to get the data and display in the demo page.

BUT, the console shows that the server side somehow runs the GET request again(not sure about this), and fetch some undefined data.

enter image description here

enter image description here

Cannot figure it out, could someone please help me?

Thanks!



via M.Guo

No comments:

Post a Comment