nodejs https callback not updating global variable [duplicate] - javascript

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

Related

Implementing CoAP protocol on node.js

Do you know any guides or tutorials about implementing CoAP protocol connection on node.js? I have to implement simple server and client application. I've checked all the resources I've found, including of course their documentation:
https://github.com/mcollina/node-coap
but it is still unclear for me.
Thank you for any help.
EDIT:
If this is implementation of server, how should look client like?
var coap = require('coap')
, server = coap.createServer()
server.on('request', function(req, res) {
res.end('Hello ' + req.url.split('/')[1] + '\n')
})
// the default CoAP port is 5683
server.listen(function() {
var req = coap.request('coap://localhost/Matteo')
req.on('response', function(res) {
res.pipe(process.stdout)
res.on('end', function() {
process.exit(0)
})
})
req.end()
})
or like this , an example for coap client
const coap = require('coap'),
bl = require('bl');
//construct coap request
var req = coap.request({
observe: false,
host: '192.168.0.93',
pathname: '/',
port: 5683,
method: 'get',
confirmable: 'true',
retrySend: 'true',
//query:'',
options: {
// "Content-Format": 'application/json'
}
})
//put payload into request
var payload = {
username: 'aniu',
}
req.write(JSON.stringify(payload));
//waiting for coap server send con response
req.on('response', function(res) {
//print response code, headers,options,method
console.log('response code', res.code);
if (res.code !== '2.05') return process.exit(1);
//get response/payload from coap server, server sends json format
res.pipe(bl(function(err, data) {
//parse data into string
var json = JSON.parse(data);
console.log("string:", json);
// JSON.stringify(json));
}))
});
req.end();
It should be like this:
const coap = require('coap')
req = coap.request('coap://localhost')
console.log("Client Request...")
req.on('response' , function(res){
res.pipe(process.stdout)
})
req.end()
Source: https://github.com/mcollina/node-coap/blob/master/examples/client.js

HTTP GET request (Node) returns 501

I'm testing fake HTTP requests on Node. But I get the same result (501) on the headers defining GET, POST methods or "FOO". I don't understand the output. Can someone give me a hint? The code:
var http = require('http');
var fs = require('fs');
var options = {
method: "FOO" //or GET
, uri: 'https://www.google.com'
};
var callback = function(response){
var exportJson= JSON.stringify(response.headers);
var arrayData =[];
response.on('data', function(data) {
arrayData += data;
});
response.on('end', function() {
console.log('THE DATA IS ' + arrayData);
});
fs.appendFile("input.txt", exportJson, function(err) {
if(err) {
return console.log(err);
}
});
}
var req = http.request(options, callback);
function test(){
for (var prop in options.method) {
//console.log(`options.method${prop} = ${options.method[prop]}`);
//console.log(req);
req;
}
}
test();
req.end();
"GET" or "FOO" methods the console says:
<h2>HTTP ERROR 500.19 - Internal Server Error</h2>
The options object has no uri key, you should use hostname.
Also, do not specify the protocol inside the host, use the key protocol.
Your object should be:
const options = {
hostname: 'www.google.com',
protocol: 'https:',
}
Remember that to use https you need to include the right module:
const https = require('https');

How to extract data from XML using node.js

how to extract data from XML type rest API using node.js?
This is the code i used to get data by sending rest api request:
//Load the request module
var request = require('request');
//Lets configure and request
request(
{
url: 'http://nemo.sonarqube.org/api/resources?resource=DEV:Fabrice%20Bellingard:org.codehaus.sonar:sonar&metrics=ncloc,coverage', //URL to hit
method: 'GET', //Specify the method
headers: { //We can define headers too
'Authorization': 'Basic ' + new Buffer( 'admin' + ':'+'admin').toString('base64'),
'Content-Type': 'MyContentType',
'Custom-Header': 'Custom Value'
}
},
function(error, response, body){
if(error) {
console.log(error);
} else {
var obj=JSON.parse(response.body);
console.log(obj.id);
}
}
)
var express = require('express');
var app = express();
var server = app.listen(3000,function (){
console.log('port 3000');
}
);
When I send the request using a browser, the result appears like:
<resources>
<resource>
<id>400009</id>
<key>DEV:Fabrice Bellingard:org.codehaus.sonar:sonar</key>
<name>SonarQube</name>
<lname>SonarQube</lname>
<scope>PRJ</scope>
<qualifier>DEV_PRJ</qualifier>
<date>2015-08-04T13:10:57+0000</date>
<creationDate/>
<copy>48569</copy>
<msr>
<key>ncloc</key>
<val>879.0</val>
<frmt_val>879</frmt_val>
</msr>
<msr>
<key>coverage</key>
<val>81.8</val>
<frmt_val>81.8%</frmt_val>
</msr>
</resource>
</resources>
I want to extract the id and print it on the console using node.js.
How I want to edit the above code?
The problem is response.body is in array format, so get the first item in the array and then its id value
//Load the request module
var request = require('request');
//Lets configure and request
request({
url: 'http://nemo.sonarqube.org/api/resources?resource=DEV:Fabrice%20Bellingard:org.codehaus.sonar:sonar&metrics=ncloc,coverage', //URL to hit
method: 'GET', //Specify the method
headers: { //We can define headers too
'Authorization': 'Basic ' + new Buffer('admin' + ':' + 'admin').toString('base64'),
'Content-Type': 'MyContentType',
'Custom-Header': 'Custom Value'
}
}, function (error, response, body) {
if (error) {
console.log(error);
} else {
var arr = JSON.parse(response.body);
var obj = arr[0];
console.log(obj.id);
}
})
var express = require('express');
var app = express();
var server = app.listen(3000, function () {
console.log('port 3000');;
});

communicate between a server and a client with node.js

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

Add parameters to HTTP POST request in Node.JS

I've known the way to send a simple HTTP request using Node.js as the following:
var http = require('http');
var options = {
host: 'example.com',
port: 80,
path: '/foo.html'
};
http.get(options, function(resp){
resp.on('data', function(chunk){
//do something with chunk
});
}).on("error", function(e){
console.log("Got error: " + e.message);
});
I want to know how to embed parameters in the body of POST request and how to capture them from the receiver module.
Would you mind using the request library. Sending a post request becomes as simple as
var options = {
url: 'https://someurl.com',
'method': 'POST',
'body': {"key":"val"}
};
request(options,function(error,response,body){
//do what you want with this callback functon
});
The request library also has a shortcut for post in request.post method in which you pass the url to make a post request to along with the data to send to that url.
Edit based on comment
To "capture" a post request it would be best if you used some kind of framework. Since express is the most popular one I will give an example of express. In case you are not familiar with express I suggest reading a getting started guide by the author himself.
All you need to do is create a post route and the callback function will contain the data that is posted to that url
app.post('/name-of-route',function(req,res){
console.log(req.body);
//req.body contains the post data that you posted to the url
});
If you want to use the native http module, parameters can be included in body this way:
var http = require('follow-redirects').http;
var fs = require('fs');
var options = {
'method': 'POST',
'hostname': 'example.com',
'path': '/foo.html',
'headers': {
},
'maxRedirects': 20
};
var req = http.request(options, function (res) {
var chunks = [];
res.on("data", function (chunk) {
chunks.push(chunk);
});
res.on("end", function (chunk) {
var body = Buffer.concat(chunks);
console.log(body.toString());
});
res.on("error", function (error) {
console.error(error);
});
});
var postData = "------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"examplekey\"\r\n\r\nexamplevalue\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW--";
req.setHeader('content-type', 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW');
req.write(postData);
req.end();

Categories