0

following problem: I am running an Nodejs server together with a mongoDB. By now I have always sent the results of my queries as json-data to the browser.

    app.get('/gesamtergebnis', function(req,res){

    User.aggregate([{$group: { 
            _id: "$Art",
            Anzahl: {$sum: "$Anzahl"}
        }

        }], function(err,docs){

        if(err){console.log(err);}
        else {res.json(docs);}  

    });

});

My results are - what is the nature of those json responses - poorly formatted. So I have set up an html-file with a table ect. and a little ng-controller to get the data in the table with ng-repeat - no problem so far.

function AppCtrl($scope, $http) {
console.log("Hello from AppCtrl")

var showTotal = function(){

    $http.get('./gesamtergebnis').success(function(response){

            console.log("I got the data I requested!");
        $scope.gesamtergebnis = response;

    });
}

}

My routing is:

app.use(express.static(__dirname + "/public")); In the public folder is my index.html

My problem is: The index.html does not receive any server response;

I need to

  • route a request to a certain html (res.sendfile does not helpt as I cannot add json data to the response) and
  • send the json data from the mongodb request within the same route command

Is there no way to redirect the server response to a certain html (also other htmls then index) endpoint with data?

What is the best way to solve this? Get the routing done on the client side with Angular? How can I do this easily?

Any help would be great!

Hucho

Hucho
  • 101
  • 2
  • 10
  • is this for you to debug the responses or do you want your api to display json on html by design? – AJS Mar 29 '16 at 13:11

1 Answers1

0

First, Express is a framework and provide the template structure, so it's good to put the files of frontend in the folder views, not in static. Static is more used for import libs, js, css... Second, for comunicate server side with frontend in node, it's recomended to use some engine, like ejs or jade; angular can be used with these too, somethink this:

Now, how to use and send json data to view, or view to server, search for similar question and consult the docs.

Community
  • 1
  • 1
BrTkCa
  • 4,703
  • 3
  • 24
  • 45