communicate between a server and a client with node.js - javascript

I have a node.js Server:-
// *********** Server that receives orders ************ //
// to use features of the http protocol. //
var http = require('http');
// initialize to empty string. //
var req = "";
// create the server that will receive an order Request. //
var server = http.createServer(function(req,res) {
res.writeHead(200, {'content-type': 'text/plain'});
// when data is successfully received, a success message is displayed. //
res.on('data', function(data){
req += data; // received data is appended. //
console.log("We have received your request successfully.");
});
});
// An error message is displayed - error event. //
server.on('error', function(e){
console.log("There is a problem with the request:\n" + e.message);
});
// server listens at the following port and localhost (IP). //
server.listen(8000, '127.0.0.1');
and then I have a node.js Client:-
var http = require("http");
var querystring = require("querystring");
var postOrder = querystring.stringify({
'msg': 'Hello World!'
});
var options = {
hostname: '127.0.0.1',
port: 8000,
path:'/order',
method:'POST',
headers:{
'Content-Type' :'application/x-www-form-urlencoded',
'Content-Length' : postOrder.length
}
};
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);
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
// write data to request body
req.write(postOrder);
req.end();
I am trying to figure out how I can make the client post its order to the server and get a response back from the server...either a success message or an error message...using command line.
currently I run the server on cmd line $ node server.js
and then a run the client $ node client.js
but i get no responses.

I think that have problems from the server:
The Server must be:
http.createServer(function(req, res) {
if (req.method == 'GET') {
} else if (req.method == 'POST') {
var body = '';
req.on('data', function(data) {
body += data;
});
req.on('end', function() {
console.log("We have received your request successfully.");
});
}
res.end("ok");
})

Related

Issue calling a https REST service in Node

I am trying to call an internally hosted REST webservice from Node.js but I am getting "problem with request: unable to verify the first certificate"
The web service is https there is no http version
There is my code
var https = require('https');
const fs = require('fs');
var options = {
host: 'path.to.application.rest.service',
port: 443,
path: '/Function',
method: 'GET',
cert: fs.readFileSync('<Path to Cert>')
};
var req = https.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);
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
req.end();
This is the certificate chain of the service
I have tried using all the different certs in the chain as the one in the options but they all fail with the same error. What am I doing wrong/missing?

Can't nest HTTP GET inside another with node.js

I want to do a very simple task, yet I am stuck!
The scenario is like this:
After a get request to my api, I want to http.get from some external site, and then send back the response from this external site to the original api request.
Obviously, the calls are asychronous so the string loremParagraph, doesn't load correctly before sending it back to the api.
Also I get the error: Error: Can't set headers after they are sent.
Here is my code:
module.exports = function(app, express) {
var myLoremRouter = express.Router();
var loremParagraph = '';
//HTTP GET accessed at localhost:8081/mylorem
myLoremRouter.get('/', function(req, res) {
// Fetch one paragpraphlorem ipsum text from http://www.faux-texte.com/text-random-1.htm
http.get("http://www.faux-texte.com/text-random-1.html", function(resp) {
resp.on('data', function(chunk) {
// console.log('BODY: ' + chunk);
var $ = cheerio.load(chunk);
loremParagraph = $('div.Texte').text();
console.log(loremParagraph);
// console.log(resp.status);
});
})
// If any error has occured, log error to console
.on('error', function(e) {
console.log("Got error: " + e.message);
});
//Finally send the result back to the api call
res.json({ message: loremParagraph });
});
return myLoremRouter;
};
Try this. Here chunks are added till we are ready to use the complete data.
https://stackoverflow.com/a/21953201/6219247
myLoremRouter.get('/', function(req, res) {
var body = '';
http.get({
host: 'www.faux-texte.com',
port: 80,
path: '/text-random-1.html'
}, function(resp) {
resp.on('data', function(chunk) {
body += chunk;
});
resp.on('end', function(chunk) {
var $ = cheerio.load(body);
loremParagraph = $('div.Texte').text();
res.json({ message: loremParagraph });
});
})
.on('error', function(e) {
// handle/send error
res.send(/*...*/);
});
});

Invalid response using https module in javaScript to fetch a public facebook profile

I am using node's https module to fetch my public profile from facebook. But i am getting 302 status code in response. Following is the code i am using:
var https = require('https');
var options = {
hostname: 'www.facebook.com',
path: '/suri.nik',
method: 'GET'
};
var results = '';
var req = https.request(options, function (res) {
console.log('STATUS CODE : ' + res.statusCode);
res.on('data', function (chunk) {
results = results + chunk;
});
res.on('end', function () {
console.log(results);
});
res.on('error', function () {
console.log('error here');
});
});
req.on('error', function (e) {
console.log('error in ur request: ' + e);
});
req.end();
I am getting STATUS CODE : 302, i should be getting status code : 200 with valid html in response of my profile. I am able to fetch the public profile from my browser or postman using the same link(www.facebook.com/suri.nik) Where lies the issue? is it the way i am making my request?

How to post data from my html page to a listener?

I'm currently designing a UI for an Automated Parking System. I currently need to test if my page sends out data from a form by sending it to a listener. I currently have this code but I'm not sure why it isn't working. Any help would be greatly appreciated.
This is my code that sends the data to a local listener.
<script>
var INPARK = {cardID: $("#ticket_num").val(), lift: 1, floor: 1};
$.ajax({
type:"POST",
url: '192.168.150.148:5007',
contentType:"application/json",
data: JSON.stringify(INPARK)
});
</script>
This is the listener code.
var HOST = '192.168.150.148'; // This should be your IP of 192.168.150.XXX
var PORT = 5007;
var http = require('http');
http.createServer(function (req, res) {
// Only listen for POST requests
if (req.method === 'POST') {
var buffer = '';
req.on('data', function (chunk) {
buffer += chunk;
});
req.on('end', function () {
var path = req.url.substring(0, req.url.indexOf('/', 1)).toUpperCase();
var json;
try {
json = JSON.parse(buffer);
} catch (err) {
//
}
if (path === '/INPARK') {
// Handle INPARK request
console.log(json);
res.write('inpark results');
} else if (path === '/OUTPARK') {
// Handle OUTPARK request
console.log(json);
res.write('outpark results');
} else {
// Do nothing - Bad request
res.write('BAD REQUEST');
}
// Close the connection
res.end();
});
}
}).listen(PORT, HOST, function () {
console.log('Listening at %s:%s', HOST, PORT);
});
Your ajax request is most likely going from port 80 or 443 to 5007, which is a cross domain request, hence it will fail,
If you want to resolve this issue, read up on CORS:
https://en.wikipedia.org/wiki/Cross-origin_resource_sharing,
and JSONP:
https://en.wikipedia.org/wiki/JSONP

nodejs https callback not updating global variable [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
I'm setting up a quick proxy server in nodejs to proxy a API request for an Angular application. The proxy endpoint is a service I do not control and does not support CORS or JSONP. For testing, I setup a dummy http server in the code example below, but in reality this is a remote domain.
I'm pretty sure my problem is due to asynchronous processing of nodejs, but I don't know how to solve this. My generic makeRequest() function seems to work ok, it gets the expected response back from the remote server. I can see the resultData string in the on('data') and on('end') event handlers with success. However, I don't know how to get the response back to the browser inside restify's req.json() method.
Help!
var restify = require('restify');
var querystring = require('querystring');
var https = require('https');
var http = require('http');
var port = '8080';
var server = restify.createServer({
name : "ProxyService"
});
var responseData = '';
// Generic request function
function makeRequest(host, endpoint, method, data, headers) {
var dataString = JSON.stringify(data);
var options = {
host: host,
path: endpoint,
method: method,
headers: headers
};
var req = https.request(options, function proxyrespond(res) {
res.on('data', function(data) {
console.log("DATA----", data);
responseData += data;
});
res.on('end', function() {
//probably need to do something here
});
});
req.end();
req.on('error', function(e) {
console.error(e);
});
console.log("OPTIONS: ", options);
console.log("DATA: ", responseData);
req.write(dataString);
req.end();
};
server.get('/getlist', function respond(req, res, next){
var headers = {'Connection': 'close',
'Content-Type': 'application/json' };
var host = 'localhost:9000';
var endpoint = '/getlist';
var auth = {auth-id: '12345', auth-token: '6789'}
var data = req.data || '';
// add authentication parms to the endpoint
endpoint += '?' + querystring.stringify(auth);
// if the request has headers, add them to the object
for (var key in res.headers) {
headers[key] = rest.headers[key];
};
makeRequest(host, endpoint, 'GET', data, headers);
res.headers = {Connection: 'close'};
res.json( responseData );
return next();
});
http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.write('request successfully proxied!' + '\n' + JSON.stringify(req.headers, true, 2));
res.end();
}).listen(9000);
server.listen(port, function(){
console.log('%s listening at %s ', server.name , server.url);
});
Return via a callback function:
// Generic request function
function makeRequest(host, endpoint, method, data, headers, callback) {
.........
var req = https.request(options, function proxyrespond(res) {
// DO NOT declare responseData as global variable
var responseData = '';
res.on('data', function(data) {
responseData = responseData + data;
});
res.on('end', function() {
// RETURN VIA CALLBACK
callback(responseData)
});
});
.........
};
server.get('/getlist', function respond(req, res, next){
.........
makeRequest(host, endpoint, 'GET', data, headers, function (responseData) {
res.headers = {Connection: 'close'};
res.json( responseData );
return next();
});
});

Categories