Get url and body from IncomingMessage? - node.js

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
});
});

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..!

Taking data from graph api with node

I am trying to connect with the facebook api to be able to get a feed of a certain page.
But I'm getting an access token error
{"error":{"message":"Invalid OAuth access token.","type":"OAuthException","code":190,"fbtrace_id":"DrEySZsEOOA"}}
I'm trying this:
Facebook.js:
var https = require('https');
exports.get = function(accessToken, apiPath, callback) {
var options = {
host: 'graph.facebook.com',
port: 443,
path: apiPath + '?access_token=' + accessToken,
method: 'GET'
};
var buffer = '';
var request = https.get(options, function(result){
result.setEncoding('utf8');
result.on('data', function(chunk){
buffer += chunk;
});
result.on('end', function(){
callback(buffer);
});
});
request.on('error', function(e){
console.log('error from facebook.get(): '
+ e.message);
});
request.end();
}
app.js:
var facebook = require('./facebook');
var http = require('http');
var server = http.createServer(app);
facebook.get('121212', '/feed/', function(data){
console.log(data);
});
server.listen(9999);
Yes, I passed the right token. I just modified it for obvious reasons hahaha
Would anyone have an idea or an example?
Thank you all
This would be the API call: https://graph.facebook.com/feed?access_token=xxx
...which is missing something important: the ID of a User, Page or Group.
For example: https://graph.facebook.com/[page-id]/feed?access_token=xxx
Keep in mind that you need different Tokens and permissions if it is about a User, Page or Group.

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);
}

Nodejs: response.write() for https.request?

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 );
});
});

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