سؤال

Check the code

var server = http.createServer(function(req, res){
    var parsedUrl = require('url').parse(req.url);
    var pathname = parsedUrl.pathname;
    pathname = pathname.replace('/get/','');

    GPSData.find({}, function(err, data) {
        if(err)
            console.log(err, data, data.length); 
        res.writeHead(200, {
                "Content-Type": "application/json",
                "Access-Control-Allow-Origin": "*"
        });
        console.log('hello');
         res.end(data);
    });

});

How to get json data from db and show in response? If I move res.end('some-json') out of GPSData.find() then I can see my page in browser but how to show data from db in response?

How to handle all this asynchronously?

هل كانت مفيدة؟

المحلول 2

Ok I found that I need to stringify my data before sending back response

var body = JSON.stringify(data);
res.end(body);

نصائح أخرى

If browser is displaying "This web page is not available" then either you should get some error messages in console, or you are simply missing server.listen(<port_number>); at the end.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top