handling json response asynchronously
题
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.
不隶属于 StackOverflow