I learned to make request with the XMPPserver by using node-xmpp library. Now i can make the request as mentioned in XMPP extensions documentations. But now i want to get the callback response for the each request (especially the XML response).
Here i have used the following code the make a request subscription (friend request) to a another user
var net = require("net");
var xmpp = require('node-xmpp');
var cl = new xmpp.Client({ jid: "one#localhost", password: "comet123$" })
cl.addListener('online', function(data) {
console.log('Connected as ' + data.jid.user + '#' + data.jid.domain + '/' + data.jid.resource)
//making subscription
var stanza = new xmpp.Element('presence',{
to: "hai#localhost",
from: "one#localhost",
type: "subscribe",
}).up
// making request
cl.send(stanza);
// nodejs has nothing left to do and will exit
cl.end()
})
I want to know, how to get the response result.
I tried with the callback functionality with as llike this,
cl.send(stanza, function(result){
console.log(result);
});
and also like this
var result = cl.send(stanza);
This returns only true,
So can anyone please tell me how do I get the callback result for the requests that we make by using the node-xmpp libarary
There is no callback or return for XMPP messages. You will have to have to set up an event listener to pick up messages coming back from the server. Add:
cl.on('stanza', function(stanza){
// Do something with the stanza
// If you want to end after the first message you get back, move this here
cl.end();
});
you can get raw data from connection
cl.connection.on("data", function (data) {
console.log('data', data.toString('utf8'));
});
Related
I'm adding tests to an application that already (partially) exists. It was written using angular and php/MariaDB in the backend. I'm now working on the http calls to the server. I plan to use jasmine with request.
I was able to make some simple tests, and can login. But I cannot test the pages that require to be logged in. I cannot find a way to add the token to the calls.
If I understand things correctly, on the received message from the sig in I should get a token that I should then use in the following calls. Who wrote the app followed the instructions given by the angular documentation which handles everything, so we are learning toguether how things really work under the hood.
Going through the received answer on the login, the only thing that looks like a token is a cookie set in the header, whose name is 'PHPSESSID'. I read and parse that cookie to get the token and make the next call like this:
request.get(
{
url: 'http://xxx.xxx.com/php/authentication/session.php',
'auth': {
'bearer': mytoken
}
}, function(err, res) {
console.log(res['body']);
done();
})
the response is what I should get if the user is NOT logged in.
Using Postman, everything works. Aparently it saves the token and uses it for the next call. That is, f I make the sign in and then make the get call to session.php I get the correct answer. I just cannot figure out what exact call postman makes or how to use the token in the next call using jasmine and request.
Since the token was passed as a cookie on the response call, what I was supposed to do was set the same cookie in the next call. Here is the code of the whole test just in case somebody needs a hand. First I sign in, then I made a call to an address that should return my email if indeed I'm logged in.
var request = require('request');
describe("login test", function() {
it("should log in", (done) => {
var user = {'email':'test#xxx.de', 'password':'blablabla'};
request.post(
{
url: 'http://xxx/test/public/php/authentication/login.php',
body: JSON.stringify(user)
},
(err, res) => {
var result = JSON.parse(res['body']);
var cookieString = res['headers']['set-cookie'];
expect(result['success']).toBe(true);
request.get(
{
url: 'http://xxx/test/public/php/authentication/session.php',
headers: {
'Cookie': cookieString
}
}, function(err, res) {
var result = JSON.parse(res['body']);
expect(result.user.email).toBe(user.email);
done();
})
});
});
});
I have a C# dotnetcore console app running on an AWS instance, and I would like to add in communication between this and my playfab cloudscript.
I can communicate from the C# console to playfab, that was simple just using the playfab nuget package. However I'm having trouble going the other way.
I only ever want to send a few different simple messages, so im not looking for anything too complex. What I have done so far, is I added the following to the start of my console application:
var listener = new HttpListener();
listener.Prefixes.Add("http://+:80/");
listener.Start();
Writer.WriteBuffer("Listening...");
HttpListenerContext context = listener.GetContext();
HttpListenerRequest request = context.Request;
// Obtain a response object.
HttpListenerResponse response = context.Response;
// Construct a response.
Writer.WriteBuffer("Context: " + context.ToString());
Writer.WriteBuffer("request: " + request.ToString());
Writer.WriteBuffer("response: " + response.ToString());
string responseString = "<HTML><BODY> Hello world!</BODY></HTML>";
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
// Get a response stream and write the response to it.
response.ContentLength64 = buffer.Length;
System.IO.Stream output = response.OutputStream;
output.Write(buffer, 0, buffer.Length);
// You must close the output stream.
output.Close();
listener.Stop();
Writer.WriteBuffer is a wrapper for writing Console.Write essentially, just formats stuff in a much better way for me. I see the "listening..." come up, so great its listening.
Now, I copied an example from playfab and just adapted it very slightly. cloudscript is in js, so here is what I am running from playfab:
var headers = {
"X-MyCustomHeader": "Some Value"
};
var body = {
input: args,
userId: currentPlayerId,
mode: "foobar"
};
var url = "http://11.111.111.1/";
var content = JSON.stringify(body);
var httpMethod = "post";
var contentType = "application/json";
// The pre-defined http object makes synchronous HTTP requests
var response = http.request(url, httpMethod, content, contentType, headers);
return { responseContent: response };
11.111.111.1 is where I put the IP address of the AWS instance (I've changed it for obvious reasons).
When running this, I get "httpRequestError": "Timeout".
When I check on AWS, I have nothing else printed out other than "Listening...", so it hasn't handled anything yet.
I'm not too sure where the problem lies to be honest.
I have a requirement to access multiple devices over IP from an HTML5 web app.
My approach to working around the cross-domain impossibility of doing this all on the client side has been to "cook" requests from the client inside of express' middleware. A route receives a get or post from the client, and then performs a get or post to the 3rd party device identified by the payload from the client.
I'm using the code to get info from a device. It works just fine when I run it directly from file inside of a client I made for testing purposes. Running directly from file avoids the CORS difficulty because the client is also the server I guess.
When I run the same code from within an express route, I get a 500 error.
Am I trying to do something impossible? I'm only about a week into node, express etc so hopefully it's something dumb and easy to solve. I'm taking fact that I haven't been able to find any other questions quite like this as an indication that there's a proper way to achieve what I need.
// post to find a camera
router.post('/find', function(req, res) {
var url = 'http://' + req.body.addr + '/cgi-bin/aw_cam?cmd=QID&res=1';
console.log(url);
$.ajax({
type: 'GET',
url: url,
dataType: 'html',
success: function (result) {
console.log('success: ' + result);
res.send(result);
},
error: function (xhr, textStatus, err) {
console.log('error: ' + textStatus);
}
});
});
Here's what logged to the server console:
http://192.168.0.10/cgi-bin/aw_cam?cmd=QID&res=1
POST /cameras/find 500 126.593 ms - 1656
Thanks in advance!
ok I found how to do this. The trick is to use Node's built-in http messaging capabilities. I found a good article on how to do this here
The code below does exactly what I wanted from within my custom route middleware. I guess I just learned that I can only use AJAX how I wanted on the client side.
This lets me abstract the hairier details of the device control protocol into the server, leaving my client apps to use JSON/AJAX model to interact with them. Success!
var http = require('http');
// post to find a camera
router.post('/find', function(req, res) {
var url = 'http://' + req.body.addr + '/cgi-bin/aw_cam?cmd=QID&res=1';
console.log(url);
http.get(url, (response) => {
console.log(`Got response: ${response.statusCode}`);
var body = '';
response.on ('data', function(d) {
body += d;
});
response.on ('end', function () {
console.log('received: ' + body);
var reply = {};
if (body.indexOf('OID:') == 0) {
reply.msg = body.slice(4);
reply.ok = true;
} else {
reply.msg = body;
reply.ok = false;
}
res.send(reply);
});
// consume response body
response.resume();
}).on('error', (e) => {
console.log(`Got error: ${e.message}`);
});
});
I have this exact question, except I'm using the restify HttpClient:
node.js write http response to stream
For clarity, I'm trying to do this:
var client = restify.createClient({
url: "http://www.google.com"
});
client.get("/", function(err,res) {
res.pipe(process.stdout);
});
It hangs for a few seconds but never writes anything to stdout. Obviously I'm trying to fetch something other than google's homepage, but for example...
I would recommend you to user request for something like this:
var request = require('request'); // npm install request
request('http://www.google.com').pipe(process.stdout);
Looking at restify's docs it seems you need to wait for the 'result' event:
var client = restify.createClient({
url: "http://www.google.com"
});
client.get("/", function(err,req) {
req.on('result',function(err2,res) {
res.pipe(process.stdout);
res.on('end',function() {
process.exit(0);
});
});
});
I have a basic Node.js http server set up as per the docs, I'm trying to create a very simple web service I can talk to with Javascript (AJAX) which I'll then hook up to Arduino. It's a test piece, I may go down the road of something else but this is proving to be fun. Anyway, here is the server-side javascript:
var http = require('http');
var _return = 'Bing Bong';
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'application/jsonp'});
//do stuff
res.end('_return(\'Hello :-)\' + _return)');
}).listen(process.env.VMC_APP_PORT || 1337, null);
And this is the client side:
function experimentFive(node) {
console.log('X5 Func started');
console.log('Calling Node.js service');
var nodeURL = node;
$.ajax({
url: nodeURL,
dataType: "jsonp",
jsonpCallback: "_return",
cache: false,
timeout: 50000,
success: function(data) {
console.log('Data is: ' + data);
$("#nodeString").text(" ");
$("#nodeString").append(data);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log('error : ' + textStatus + " " + errorThrown);
}
});
}
experimentFive('http://fingerpuk.eu01.aws.af.cm/');
This works, I get the data back but not as I'd expect. What I'd like to be able to do is change some data server side and receive that back. I get back the string in the res.end plus:
function () {
responseContainer = arguments;
}
Instead of the variable's data. No matter how I try to get that data back, it is either undefined or this response.
From research I think the variable is not having it's data set before the callback fires, so it's empty. But if I set an initial value the data is still undefined.
Am I missing something very simple here? Should I just go back to C#?
Cheers.
One possible way of accomplishing this would be to use ExpressJS with NodeJS to handle routing your endpoints. By doing this you can set up routes such as GET /media/movies/, fire an AJAX request to this route, then have it return JSON data that you can handle on your app.
Here's an example of ExpressJS routing in an app that I made:
var groups = require('../app/controllers/groups');
// find a group by email
app.post('/groups/find', groups.searchGroupsByEmail);
Here is a great tutorial that I used when getting started with Express. It walks through the entire process from installing Node.JS (which you've already done) to setting up the ExpressJS routing to handle incoming HTTP requests.
Creating a REST API using Node.js, Express, and MongoDB