jaeger endpoint isnt recieving data using jaeger Node.js client - javascript

Was trying to connect to jaeger using HTTP request using nodejs but the spans are not reaching the jaeger endpoint. please help with this code snippet.,
var initTracer = require('jaeger-client').initTracer;
var config = {
'serviceName': 'servicename1',
'reporter': {
'collectorEndpoint': 'http://jaeger-collector:14268/api/traces',
}
};
var options = {
tags: {
'servicename1': '1.0'
}
};
var tracer = initTracer(config, options);
var express = require('express');
var app = express();
var http = require('http');
var server = http.createServer(app);
app.get('/', (req, res) => {
const span = tracer.startSpan('http_request');
res.send('Hello Jaeger');
span.log({'event': 'request_end'});
span.finish();
});
app.get('/', function(req, res) {
res.send("Hello World!");
});
server.listen(3000);
console.log('Express server started on port %s', server.address().port);
Any help would be much appreciated!

Got it! We need to enable sampling strategy to reach the collector endpoint.
var initTracer = require('jaeger-client').initTracer;
var config = {
'serviceName': 'Jaeger_Service',
'reporter': {
'collectorEndpoint': 'http://jaeger-collector:14268/api/traces',
},
'sampler': {
'type': 'const',
'param' : 0.1
}
};
var options = {
'logger': {
'info': function logInfo(msg) {
console.log('INFO ', msg)
},
'error': function logError(msg) {
console.log('ERROR', msg)
}
}
};
var tracer = initTracer(config, options);
var express = require('express');
var app = express();
var http = require('http');
var server = http.createServer(app);
app.get('/', (req, res) => {
const span = tracer.startSpan('http_request');
res.send('Hello Jaeger');
span.log({'event': 'request_end'});
span.finish();
});
server.listen(8000);
console.log('Express server started on port %s', server.address().port);

Related

unable to send post request using socket.io

here i am sending data from socket client to socket server and after receiving the request it has to send to node api
**the issue is im getting null ** on calling the socket server
below is my code
Socket Client
socket.connect();
socket.emit("posreq",JSON.stringify({ "title": "data"}));
Socket Server
var http = require('http'),
io = require('socket.io'), // for npm, otherwise use require('./path/to/socket.io')
request = require('request'),
cors = require('cors'),
server = http.createServer(function (req, res) {
// your normal server code
res.writeHead(200, {
'Content-Type': 'application/json'
});
res.end('Hello world');
});
server.listen(4000);
// socket.io
var socket = io.listen(server);
socket.on('connection', function (client) {
// new client is here!
client.on('posreq', function (postdata) {
request.post("http://localhost:3000/book", {
body: postdata
}, function (res) {
console.log(res);
client.send("post req called",postdata);
});
});
client.on('disconnect', function () {
console.log('connection closed');
});
});
Node api
const express = require('express')
const bodyParser = require('body-parser');
const cors = require('cors');
const app = express()
const port = 3000
let books = [{
"title": "Eloquent JavaScript, Second Edition",
}];
app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.post('/book', (req, res) => {
const book = req.body;
// output the book to the console for debugging
console.log(book);
// books.push(book);
res.json('Book is added to the database');
});
I tried but unable to understand the issue
Note : How can i convert the Socket server to express js code
As far I understand you are willing to use express instead of HTTP and that will solve your problem. And in the below code, I have used express as well as HTTP. Try code below
const express=require("express")
const app=express()
const server=require("http").createServer(app)
const socket=require("socket.io")(server)
server.listen(4000,()=>console.log(`Listening to port 4000`))
socket.on('connection', function (client) {
client.on('posreq', function (postdata) {
request.post("http://localhost:3000/book", {
body: postdata
}, function (res) {
console.log(res);
client.send("post req called",postdata);
});
});
client.on('disconnect', function () {
console.log('connection closed');
});
});
May be you need few modification,
Request is depricated so better to use axios or other alternative.
const express = require("express")
const bodyParser = require("body-parser")
const axios = require('axios')
const app = express()
const httpServer = require("http").createServer(app)
const socket = require("socket.io")(server)
app.use(bodyParser.json({ limit: '16mb' }));
app.use(bodyParser.urlencoded({ limit: '16mb', extended: true, parameterLimit: 50000 }));
app.get('/', (req,res)=> res.send("Hello world"));
socket.on('connection', function (socket) {
socket.on('posreq', async (body) => {
try {
const { data } = await axios.post("http://localhost:3000/book", { body })
socket.send("post req called", data);
} catch (error) {
socket.send("post req error", error);
}
});
socket.on('disconnect', function () {
console.log('connection closed');
});
});
httpServer.listen(3000, () => console.log(`Spinning 3000`))

Only “polling” on socket.io

I have two applications hosted in openshift v2, both have the same code, the first uses Node.js 0.10 and socket.io works perfectly. The second application uses Node.js 8.2.1 but socket.io doesn't work and I get the same error as in these other sites:
Client side receive polling on socket.io
Socket.io cannot connect, resorts to “polling”
Socket.io connection reverts to polling, never fires the 'connection' handler
I tried to make the answers, but without result, if the code is the same in my two applications.. What can be failing? It's necessary to make some changes in the new version of Node.js?
This is the relevant code in my application and information about it:
Both app run perfectly on ports 8080 or 3000.
SERVER
App.js
var fs = require('fs');
var express = require('express');
var app = express();
var server = require('http').Server(app);
var bodyParser = require ('body-parser');
var jwt = require('jsonwebtoken');
var io = require('socket.io')(server);
var server_ip_address = process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1';
var server_port = process.env.OPENSHIFT_NODEJS_PORT || 3000;
server.listen(server_port, server_ip_address, function () {
console.log( "APP Listening on: " + server_ip_address + ":" + server_port )
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static(__dirname + '/'));
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function (socket) {
console.log('USUARIO CONECTADO');
socket.on('coordenada', function (data) {
io.emit('notificacion', {
Latitud: data.latitudData,
Longitud: data.longitudData,
Nombre: data.name
});
});
});
CLIENT
Controllers.js
app.controller('mapCtrl', function ($scope, NgMap, socket) {
vm = this;
socket.on('notificacion', function(data) {
console.log("coordenada recibida: ", data.Latitud +","+ data.Longitud +" de "+ data.Nombre);
var name = data.Nombre;
vm.transportistas = [
{id:'1', nombre: data.Nombre, posicion:[data.Latitud, data.Longitud]}
];
NgMap.getMap().then(function(map) {
vm.map = map;
google.maps.event.trigger(vm.map, 'resize');
});
});
vm.wayPoints = [
{location: {lat:39.502223, lng: -0.363244}},
];
NgMap.getMap()
.then(function(map) {
vm.map = map;
vm.map.setZoom(6);
vm.map.setCenter(new google.maps.LatLng(40, -4));
});
vm.mostrarDetalles = function(e, transportista) {
vm.transportista = transportista;
vm.map.showInfoWindow('foo-iw', transportista.id);
};
});
factorias.js
app.factory('socket', ['$rootScope', function($rootScope) {
var socket = io.connect();
return {
on: function(eventName, callback){
socket.on(eventName, callback);
},
emit: function(eventName, data) {
socket.emit(eventName, data);
}
};
}]);
And I get this on web console ONLY in the app with Node.js 8.2.1:
GET http://localhost/socket.io/?EIO=3&transport=polling&t=1448850081140-15
GET http://localhost/socket.io/?EIO=3&transport=polling&t=1448850080247-12
GET http://localhost/socket.io/?EIO=3&transport=polling&t=1448850080252-13
etc...
**I'm sorry for my English.

Error: Failed to lookup view 'socket.io' in views directory

I have a problem with my nodejs server. Here is my code
server.js
global.jQuery = global.$ = require('jquery');
var express = require('express'),
path = require('path'),
menu = require("./routes/menu");
var sql = require("mssql");
var http = require("http");
var io2 = require("io");
var app = express();
var serve = http.createServer(app);
var io = require('socket.io')(serve);
var recordset2;
var port = 8080;
app.configure(function () {
app.set('views', __dirname + '/views');
app.set('view engine','jade');
/* app.use(express.favicon());*/
app.use(app.router);
app.use(express.static(path.join(__dirname+'public')));
});
app.get('/:viewname', menu.viewname);
io.on('connection', function (socket) {
socket.on('disconnect', function () {
console.log('user disconnected');
});
socket.on('chat', function (msg) {
socket.broadcast.emit('chat', msg);
});
});
var dbConfig = {
server: "localhost",
database: "MyDatabase",
user: "sa",
password: "sa",
port: 1433
};
function getConnected() {
var conn = new sql.Connection(dbConfig);
conn.connect().then(function () {
var req = new sql.Request(conn);
req.query("SELECT * FROM Countries").then(function (recordset) {
console.log("Recordset:", recordset);
conn.close();
}).catch(function (err) {
console.log("Error!!!!");
console.log(err);
conn.close();
});
}).catch(function (err) {
console.log("Error!!!! ----");
console.log(err);
});
}
getConnected();
app.listen(port);
client's code
var socket = io();
$(function () {
$('#get-button').on('click', function () {
console.log("CLICK");
var msg = "HIIII";
socket.emit('chat', msg);
});
});
I'm trying to make a connection between server and client by socket, but it returns me the following error:
Error: Failed to lookup view 'socket.io' in views directory C:\Radio/views;
at Function.app.render (C:\Radio\node_modules\express\lib\application.js:493:17)
at ServerResponse.res.render (C:\Radio\node_modules\express\lib\response.js:798:7)
at exports.viewname (C:\Radio\routes\menu.js:2:9)
at callbacks (C:\Radio\node_modules\express\lib\router\index.js:164:37)
at param (C:\Radio\node_modules\express\lib\router\index.js:138:11)
at param (C:\Radio\node_modules\express\lib\router\index.js:135:11)
at pass (C:\Radio\node_modules\express\lib\router\index.js:145:5)
at Router._dispatch (C:\Radio\node_modules\express\lib\router\index.js:173:5)
at Object.router (C:\Radio\node_modules\express\lib\router\index.js:33:10)
at next (C:\Radio\node_modules\express\node_modules\connect\lib\proto.js:193:15
Could you help me understand why? I saw there is another similar topics but none of the solutions there helped.
I found a solution two minutes after posting this topic.
global.jQuery = global.$ = require('jquery');
var express = require('express'),
path = require('path'),
menu = require("./routes/menu");
var sql = require("mssql");
var http = require("http");
var io2 = require("io");
var app = express();
var port = 8080;
var ser = app.listen(port); //<-----------This solved my problem.

Node testing and console.log issues

I've set up a simple node server and test program from the Node: up and running book. It seems to be working fine when I trace it through with debug but I'm curious why console.log doesn't output anything to the terminal.
Server, app.js
var express = require('express');
var http = require('http');
var app = express();
app.set('port', process.env.PORT || 8000)
app.use(express.urlencoded());
app.use(express.json());
app.use(express.logger('dev'));
var tweets = [];
app.get('/', function (req, res) {
res.send('Welcome to Node Twitter');
});
app.post('/send', function(req, res) {
if (req.body && req.body.tweet) {
tweets.push(req.body.tweet);
res.send({status:"ok", message:"Tweet received"});
} else {
// no tweet ?
res.send({status:"nok", message:"No tweet received"});
}
});
app.get('tweets', function (req, res) {
res.send(tweets);
});
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
Test script, test.js
var http = require('http');
assert = require('assert');
var opts = {
host: 'localhost',
port: 8000,
path: '/send',
method: 'POST',
headers: {'content-type':'application/x-www-form-urlencoded'}
}
var req = http.request(opts, function(res) {
res.setEncoding('utf8');
console.log("Sending test");
var data = "";
res.on('data', function(d) {
data += d;
})
res.on('end', function() {
assert.strictEqual(data, '{"status":"ok", "message":"Tweet received"}');
console.log("test");
})
})
req.write('tweet=test')
req.end
Would love some advice.
The event end never gets fired because you don't call the function req.end. You maintains the http request/connection open. You never finish it.
Try instead:
req.end();
Think about the difference between:
console.log('HI');
console.log;

Nodejs Publish from Client in pub/sub

I am trying to build a small app in nodejs to publish and subscribe. I am stucked in how I can publish from client side. Here is the code I have.
Here is my server code (server.js)
var express = require('express'),
app = express(),
http = require('http'),
server = http.createServer(app);
app.use(express.bodyParser());
app.get('/', function(req, res) {
res.sendfile(__dirname + '/public/index.html');
});
app.post('/publish/:channel/:event/', function(req, res) {
console.log("**************************************");
var params = req.params;
console.log(req.params);
console.log(req.body);
var data = req.body;
console.log("**************************************");
var result = io.sockets.emit(params.channel,{event:params.event,data:data});
//console.log(result);
console.log("**************************************");
res.sendfile(__dirname + '/public/index.html');
});
//include static files
app.use(express.static(__dirname + '/public'));
server = server.listen(3000);
var io = require('socket.io').listen(server);
io.sockets.on('connection', function (s) {
socket = s
socket.emit('c1', { hello: 'world' });
socket.on('test', function (data) {
socket.emit('c1', { hello: 'world' });
console.log('test');console.log(data);
});
});
And here is client code
var narad = {};
narad.url = 'http://192.168.0.46:3000';
narad.lisentingChannels = {}
var socket = io.connect(narad.url);
function Channel(channelName) {
this.channelName = channelName; //serviceObject is the object of
this.events = {};
};
Channel.prototype.bind = function (event, callback) {
this.events[event] = callback;
};
narad.subscribe = function (channelName) {
var channel = new Channel(channelName)
this.lisentingChannels[channelName] = channel;
socket.on(channelName, this.callbackBuilder(channel))
return this.lisentingChannels[channelName];
}
narad.callbackBuilder = function (channel) {
return function (data) {
var callback = channel.events[data["event"]];
callback(data.data);
}
}
You can use the emit method on both the client and the server websocket connections, taken from Socket.io:
var socket = io.connect(narad.url);
socket.emit('publish', 'message');
Then on your server you listen for the message:
socket.on('publish', function (data) {
// Emit the published message to the subscribers
socket.emit('subscribers', data);
console.log(data);
});
This way you are using the bi-directional communication of websockets without having to use some POST api.

Categories