Nodejs: response.write() for https.request? - node.js

Hi I am trying to make an https.request to an API server. I can receive the chunk and print it in the console. How can I write it directly into html and show it in the browser?
I tried to look for the equivalent of response.write() of http.request but didn't find one. res.write(chunk) will give me a TypeError. How can I do this?
var req = https.request(options_places, 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); // Console can show chunk data
res.write(chunk); // This gives TypeError: Object #<IncomingMessage> has no method 'write'
});
});
req.end();
req.on('error', function(e){
console.log('ERROR?: ' + e.message );
});

First you have to create server and listen on some port for the requests.
var http = require('http');
http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('Whatever you wish to send \n');
}).listen(3000); // any free port no.
console.log('Server started');
Now it listens incoming connections at 127.0.0.1:3000
For specific url use .listen(3000,'your url') instead of listen(3000)

This works for me.
app.get('/',function(req, res){ // Browser's GET request
var options = {
hostname: 'foo',
path: 'bar',
method: 'GET'
};
var clientRequest = https.request(options, function(clientResponse){
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
clientResponse.setEncoding('utf8');
clientResponse.on('data', function(chunk){
console.log('BODY: ' + chunk);
res.write(chunk); // This respond to browser's GET request and write the data into html.
});
});
clientRequest.end();
clientRequest.on('error', function(e){
console.log('ERROR: ' + e.message );
});
});

Related

A ECONNREFUSED error of the node. Js

My Node app is throwing a ECONNREFUSED error. The port should not be in use. Any ideas?
console.info('-----http-----');
console.info();
var http = require('http');
var options = {
hostname: 'localhost',
port: 6860,
path: '/',
method: 'post'
};
var req = http.request(options, function(res) {
console.log('status:' + res.statusCode);
res.setEncoding('UTF-8');
res.on('data', function(chunk) {
console.log('body:' + chunk);
});
});
req.on('error', function(e) {
console.log('problem with request:' + e.message);
});
req.end();
Seems you are trying to send post request to one of the URL (localhost),
the code you posted that alone will not work, somewhere your server should run i.,e localhost:6860
For that just you need to create a server which runs on the port 6860.
Execute this simple server.js file in separate terminal then run "localhost:6860" in your browser.
Then run your code in separate terminal, it will execute properly. Check your both terminals you will get the difference.
**server.js**
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {
'Content-Type': 'text/plain'
});
console.log(req.url)
console.log(req.method)
res.end('okay');
}).listen(6860, "localhost");
$node server.js
Hope it will help you..!

nodejs http request pending forever

Im new to nodejs. Just trying to get a http.request function running.
It should listen to the port 3523 on localhost. When people go to the url of http://127.0.0.1:3523/remote?url=www.google.com it should take the visitor to www.google.com
This is the code:
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
var urlinfo = url.parse(req.url, true),
params = urlinfo.query;
if (req.url.match(/^\/remote/)) {
console.log("Remote");
http.request({host: "www.google.com"}, function(response){
console.log('STATUS: ' + res.statusCode);
var str = '';
response.on('data', function(chunk){
str += chunk;
});
response.on('end', function(){
res.end(str);
})
});
}
}).listen(3523);
Now when i enter the url it just pending forever. What did i miss or what did i do wrong?
Thanks in advance.
to redirect simply use response.redirect method
if (req.url.match(/^\/remote/)) {
console.log("Remote");
response.redirect(req.url);
}

Get url and body from IncomingMessage?

I am very new to node. I am at the point at which I have a simple server which should just print the request query and the request body which it takes. What I've understood is that the "handle request" function actually doesn't return a request object, rather an IncomingMessage object.
There are two things which I don't understand: How to obtain the query string and the body.
I get just the path, without the query and undefined for the body.
Server Code:
var http = require('http');
var server = http.createServer(function (request, response) {
console.log("Request query " + request.url);
console.log("Request body " + request.body);
response.writeHead(200, {"Content-Type": "text/plain"});
response.end("<h1>Hello world!</h1>");
});
server.listen(8000);
console.log("Server running at http://127.0.0.1:8000/");
Request code:
var http = require('http');
var options = {
host: '127.0.0.1',
port: 8000,
path: '/',
query: "argument=narnia",
method: 'GET'
};
var req = http.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('response: ' + chunk);
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
req.write("<h1>Hello!</h1>");
req.end();
Please note that I am a complete beginner. I am not looking for express only solutions.
The reason that you do not see the query string at request.url is that you aren't sending one correctly. In your request code, there is no query property of options. You must append your querystring to the path.
path: '/' + '?' + querystring.stringify({argument: 'narnia'}),
For your second question, if you want the full request body, you must read from the request object like a stream.
var server = http.createServer(function (request, response) {
request.on('data', function (chunk) {
// Do something with `chunk` here
});
});

How to get status from Monit from a NodeJS program?

I'm trying to get the status from Monit from a NodeJS program. In my monitrc I have it set to use port 2812, but I'm not sure what to do in my node program. Any advice would be highly appreciated.
I'll add that I am currently clueless, but I've tried:
var net = require('net');
var client = net.connect({port: 2812},
function() { //'connect' listener
console.log('client connected');
client.write('monit status');
});
client.on('data', function(data) {
console.log(data.toString());
client.end();
});
client.on('end', function() {
console.log('client disconnected');
});
Which outputs:
client connected
HTTP/1.0 400 Bad Request
Date: Tue, 04 Dec 2012 17:03:15 GMT
Server: monit 5.3.2
Content-Type: text/html
Connection: close
<html><head><title>Bad Request</title></head><body bgcolor=#FFFFFF><h2>Bad Request</h2>Cannot parse request<p><hr><a href='http://mmonit.com/monit/'><font size=-1>monit 5.3.2</font></a></body></html>
client disconnected
This is more than nothing, since it actually lists monit as the server, but I have no idea how to make it work.
I figured it out. Turns out what I wanted to do was:
var http = require('http');
var options = {
hostname: '127.0.0.1',
port: 2812,
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 (data) {
console.log('BODY: ' + data);
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
req.end();

Difficulties with node.js proxy

I am attempting to make a GET request for a single image on another server from node.js.
var http = require('http');
var site = http.createClient(80, '192.168.111.190');
var proxy_request = site.request('/image.png');
proxy_request.on('response', function (proxy_response) {
console.log('receiving response');
proxy_response.on('data', function (chunk) {
});
proxy_response.on('end', function () {
console.log('done');
});
});
And even with this code, I can't get the "receiving response" message to print out. Outside of node, I can do a curl http://192.168.111.190/image.png just fine, but is there something else I might be missing?
for get requests try the http.get API http://nodejs.org/docs/v0.4.9/api/http.html#http.get
var http = require('http');
var options = {
host: '192.168.111.190',
port: 80,
path: '/image.png'
};
http.get(options, function(res) {
console.log("Got response: " + res.statusCode);
}).on('error', function(e) {
console.log("Got error: " + e.message);
});

Resources