I am using the sample code from nodejs.org and trying to send the response to the browser .
var http = require("http");
var port = 8001;
http.createServer().listen(port);
var options = {
host: "xxx",
port: 5984,
//path: "/_all_dbs",
path: "xxxxx",
method: "GET"
};
var req = http.request(options, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('BODY: ' + chunk);
var buffer = "";
buffer += chunk;
var parsedData = JSON.parse(buffer);
console.log(parsedData);
console.log("Name of the contac开发者_StackOverflowt "+parsedData.name);
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
req.write("hello"); req.end();
But req.write("hello") just does not output the string to the browser ? Is this not the right way ? can someone also tell me how to output the response to the html in views folder so that i can populate the response to the static html .
Try this:
var http = require('http');
var options = {
host: "127.0.0.1",
port: 5984,
path: "/_all_dbs",
method: "GET"
};
http.createServer(function(req,res){
var rq = http.request(options, function(rs) {
rs.on('data', function (chunk) {
res.write(chunk);
});
rs.on('end', function () {
res.end();
});
});
rq.end();
}).listen(8001);
Edit:
This node script saves the output to a file:
var http = require('http');
var fs=require('fs');
var options = {
host: "127.0.0.1",
port: 5984,
path: "/_all_dbs",
method: "GET"
};
var buffer="";
var rq = http.request(options, function(rs) {
rs.on('data', function (chunk) {
buffer+=chunk;
});
rs.on('end', function () {
fs.writeFile('/path/to/viewsfolder/your.html',buffer,function(err){
if (err) throw err;
console.log('It\'s saved!');
});
});
});
rq.end();
精彩评论