Hi i'm unable to figure out how to connect to rabbitmq using Mocha & chai framework.
I've installed rabbitmq & erlang on my local & trying to connect to rabbitmq by starting the server on local.
The code i'm using is as below:
var chai = require('chai');
var chaiHttp = require('chai-http');
var request = chai.request;
var should = chai.should();
var expect = chai.expect;
var assert = chai.assert;
var supertest = require('supertest');
var fs = require('fs');
var amqp = require('amqplib/callback_api');
//Plugin for HTTP, etc.
chai.use(chaiHttp);
process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = '0';
describe("Testing RabbitMQ : ", function () {
it("Send a message : ", function (done) {
amqp.connect('amqp://localhost:15672/', function (err, conn) {
conn.createChannel(function (err, ch) {
var q = 'hello';
ch.assertQueue(q, { durable: false });
// Note: on Node 6 Buffer.from(msg) should be used
ch.sendToQueue(q, new Buffer('Hello World!'));
console.log(" [x] Sent 'Hello World!'");
});
setTimeout(function () { conn.close(); process.exit(0) }, 500);
});
done();
});
it("Receive a message", function (done) {
amqp.connect('amqp://localhost:15672/', function (err, conn) {
conn.createChannel(function (err, ch) {
var q = 'hello';
ch.assertQueue(q, { durable: false });
console.log(" [*] Waiting for messages in %s. To exit press CTRL+C", q);
ch.consume(q, function (msg) {
console.log(" [x] Received %s", msg.content.toString());
}, { noAck: true });
});
});
done();
});
})
So is there any other way to connect to rabbitmq & publish a message?
I've tried with amqp library, any sample code for connecting to rabbitmq will be helpful.
Can anyone make me understand how to connect to a specific queue to send a message, where the message can be published.
Any help would be really appreciated. Thank you.
You are specifying the wrong port. The default amqp port is 5672. If you are not changing the default port then you don't need to specify the port in amqp server url. That is instead of amqp://localhost:15672/, you can simply specify the url as amqp://localhost. I would like to give a working program for How to publish a message to rabbitmq using Mocha framework?.
I run the RabbitMQ server in my system using docker
docker run -d --hostname rabbit1 --name rabbit1 -e RABBITMQ_ERLANG_COOKIE=rabbitcluster -p 30000:5672 -p 30001:15672 rabbitmq:management
Then
// test.js
var chai = require('chai')
var amqp = require('amqplib/callback_api');
var chaiHttp = require('chai-http')
var should = chai.should()
chai.use(chaiHttp);
var config={
protocol: 'amqp',
hostname: 'localhost',
port: 30000,
username: 'guest',
password: 'guest',
}
var q="ex.queue";
var msg = "Hello World!";
describe('Testing RabbitMQ',function(){
it('Sending Message to RabbitMQ Server',function(done){
amqp.connect(config, function(err, conn) {
if(err){
console.log("connection error");
return;
}
conn.createConfirmChannel(function(err, ch) {
if(err){
return;
}
ch.assertQueue(q, {durable: true});
ch.sendToQueue(q, new Buffer(msg), {persistent: true},
function(err){
if(err){
console.log("msg resend err==>",err);
return;
}
else{
console.log(" [x] reSent '%s'", msg);
}
});
});
done();
setTimeout(function() { conn.close();}, 500);
});
});
});
Related
I am new to node.js and try to connect to my database. I am using VS 2019 and when debugging while connecting to the local database (which is a copy from that on the server), it works fine and return the data but when I debug it when refer to the database on the server it didn't work.
I got the following error:
ConnectionError: Failed to connect to SQL5075.site4now.net:1433 - 12924:error:1425F102:SSL routines:ssl_choose_client_version:unsupported protocol:c:\ws\deps\openssl\openssl\ssl\statem\statem_lib.c:1994:
Can anyone help? Thank you
This is my code in VS2019:
var app = require('express')();
app.get('*', (req, res) => {
var sql = require("mssql");
// config for your database
var config = {
//This connection works fine
//user: 'sa',
//password: 'xxxxxxx',
//server: 'localhost',
//database: 'DB_9BD4_info'
// this connect to the server.
user: 'DB_admin',
password: 'xxxxxxx',
server: 'SQL50.xxxxxxx.net',
database: 'DB_9BD4_info'
};
(async function () {
try {
let pool = await sql.connect(config)
let result1 = await pool.request()
.query('select * from info')
// console.dir(result1)
// send records as a response
res.send(result1);
} catch (err) {
console.log(err)
}
})();
sql.on('error', err => {
// error handler
console.log(err);
});
});
//start listening
var port = process.env.PORT || 5321;
app.listen(port, function () {
console.log('Application started on ' + new Date());
console.log("Listening on " + port);
});
I've got the same error. What worked for me was this config object:
const sqlConfig = {
server: 'server',
database: 'database',
user: 'user',
password: 'password',
pool: {
max: 10,
min: 0,
idleTimeoutMillis: 30000,
},
options: {
instanceName: 'instance name',
trustServerCertificate: true,
encrypt: false,
},
};
I'm trying to run a test suite with mocha, the goal is to start the server beforeEach test case and then
close it afterEach test case.
But for some reason when the afterEach case ignites I get the following error:
Error [ERR_SERVER_NOT_RUNNING]: Server is not running.
The test case passes which means the server is up and running.
I Export the server like this from my app.js file:
var server = app.listen(3000, function () {
var port = server.address().port;
console.log("Example app listening at port %s", port);
});
module.exports = server; // Export server in order to use it in test files
My test file:
describe("loading express", function () {
var server;
before(function (done) {
User.deleteMany(done);
});
beforeEach(function () {
server = require("../app");
});
afterEach(function (done) {
server.close(done);
});
describe("Create user account with valid email address", function () {
describe("Route: POST /signup", () => {
it("201 HAPPY PATH", (done) => {
chai
.request(server)
.post("/signup")
.send({
email: "test23222#test.test",
password: "12345678",
firstname: "testtest",
lastname: "testtest",
})
.end((err, res) => {
res.should.have.status(201);
done();
});
});
});
});
});
I believe I need to export a promise.
This is what I got so far:
var server = new Promise(function (resolve, reject) {
app.listen(3000, function () {
var port = server.address().port;
console.log("Example app listening at port %s", port);
resolve();
});
}
module.exports = server; // Export server in order to use it in test files
in test suite:
var server = require('./app.js')
server.then(function() {
....
}
The server is closed by chai-http every time a request is served.
From the chai-http docs:
If you want to keep the server open, perhaps if you’re making multiple requests, you must call .keepOpen() after .request(), and manually close the server down:
E.g:
chai
.request(server)
.keepOpen() // <-- Here
.post("/signup")
.send({
email: "test23222#test.test",
password: "12345678",
firstname: "testtest",
lastname: "testtest",
})
Error: Handshake terminated by server: 403 (ACCESS-REFUSED) with message "ACCESS_REFUSED - Login was refused using authen
tication mechanism PLAIN. For details see the broker logfile."
I tried authMechanism individually ('PLAIN', 'AMQPLAIN', 'EXTERNAL') but i'm getting same error.
Unable to create connection with rabbitMQ
var raabitmqSettings = {
protocol: 'amqp',
hostname: '10.250.18.31',
port: 5672,
username: 'sam',
password: 'sam#123',
vhost: '/',
authMechanism: ['PLAIN', 'AMQPLAIN', 'EXTERNAL']
}
amqp.connect(raabitmqSettings, function(err, conn) {
conn.createChannel(function(err, ch) {
console.log("\n\n" + ch);
}
}
Where can i see log file in rabbit mq or how enable logs in rabbitMQ?
Is it right way to create connection? Is there any setting in rabbitMQ server?
Use following code at receiver end
const open = await amqp.connect(setting);
var ch = await open.createChannel();
await ch.assertExchange("cronService", "direct");
var q = 'CronQueue';
ch.assertQueue(q, { durable: true });
ch.consume(q, async function(msg) {
console.log(" [x] Received %s", msg.content.toString());
}, { noAck: true });
return something;
I want to connect and Request from MSSQL using nodejs to link it with magento.
I Am trying to fix it for days now but it ends on the same way...
This is my Error Code:
Connected
{ RequestError: Requests can only be made in the LoggedIn state, not the Connecting state
at RequestError (C:\Workspace\Visual-Code\nodeApi\node_modules\tedious\lib\errors.js:34:12)
at Connection.makeRequest (C:\Workspace\Visual-Code\nodeApi\node_modules\tedious\lib\connection.js:1423:33)
at Connection.execSql (C:\Workspace\Visual-Code\nodeApi\node_modules\tedious\lib\connection.js:1194:19)
at executeStatement (C:\Workspace\Visual-Code\nodeApi\nodeapi.js:41:20)
at Connection.<anonymous> (C:\Workspace\Visual-Code\nodeApi\nodeapi.js:14:9)
at emitOne (events.js:116:13)
at Connection.emit (events.js:211:7)
at Connection.socketError (C:\Workspace\Visual-Code\nodeApi\node_modules\tedious\lib\connection.js:869:14)
at C:\Workspace\Visual-Code\nodeApi\node_modules\tedious\lib\connection.js:739:25
at GetAddrInfoReqWrap.callback (C:\Workspace\Visual-Code\nodeApi\node_modules\tedious\lib\connector.js:68:18)
message: 'Requests can only be made in the LoggedIn state, not the
Connecting state',
code: 'EINVALIDSTATE' }
I searched a lot and found similar problems but nothing solved it...
This is my Code maybe you can help me Spot the mistake.
var Connection = require('tedious').Connection;
var config = {
userName: 'Cool userName',
password: 'awesome password',
server: 'amazing server',
options: {
database: 'database',
}
};
var connection = new Connection(config);
connection.on('connect', function(err) {
// If no error, then good to proceed.
console.log("Connected");
executeStatement();
});
var Request = require('tedious').Request;
var TYPES = require('tedious').TYPES;
function executeStatement() {
request = new Request("select * from Artikelstamm;", function(err) {
if (err) {
console.log(err);}
});
var result = "";
request.on('row', function(columns) {
columns.forEach(function(column) {
if (column.value === null) {
console.log('NULL');
} else {
result+= column.value + " ";
}
});
console.log(result);
result ="";
});
request.on('done', function(rowCount, more) {
console.log(rowCount + ' rows returned');
});
connection.execSql(request);
}
Set Firewall rule to your DB by adding CleintIP. In Azure SQLDB, there is SET FIREWALL RULE button. You can use it to add IP.
Add this event to your request
request.on("requestCompleted", function () {
connection.close();
resolve(result);
});
I am trying to get a simple video chat working with PeerJS. I want to send audio between Firefox on a pc and Firefox on Android. I can get the call running (call.on) and I can view local video but for some reason the media just doesn't come through to the other user. Currently I am getting the error:
ICE failed, see about:webrtc for more details
I have a server which in its simple version is as such:
var ip = require('ip');
var PeerServer = require('peer').PeerServer;
var port = 9000;
var server = new PeerServer({port: port, allow_discovery: true});
Then I have two clients, one for the pc that makes the call:
var SERVER_IP = window.location.hostname;
var SERVER_PORT = 9000;
var localStream = "";
var peerID = "pc"
var peerConnectionID = "and"
var remoteVideo = document.querySelector('#rremote-video');
var localVideo = document.querySelector('#llocal-video');
var peer = new Peer(peerID, {host: SERVER_IP, port: SERVER_PORT});
var conn = peer.connect(peerConnectionID);
var getUserMedia = navigator.mediaDevices.getUserMedia({ video: true, audio: true })
.then(stream => localVideo.srcObject = stream)
.then(stream => localStream = stream)
.catch(e => console.log(e.name + ": "+ e.message));
waitForElement();
function waitForElement(){
if(localStream != ""){
conn.on('open', function(){
conn.send('hi from PC!');
});
peer.on('connection', function(conn) {
conn.on('data', function(data){
console.log(data);
});
});
console.log("we have a stream: "+localStream);
var call = peer.call(peerConnectionID, localStream);
console.log("Calling "+peerConnectionID);
call.on('stream', function(remotestream) {
console.log("Call on.");
remoteVideo.srcObject = remotestream;
});
}
else{
setTimeout(function(){
waitForElement();
},750);
}
}
And the one that answers the call is:
var SERVER_IP = window.location.hostname;
var SERVER_PORT = 9000;
var localStream = "";
var peerID = "and"
var peerConnectionID = "pc"
var remoteVideo = document.querySelector('#rremote-video');
var localVideo = document.querySelector('#llocal-video');
var remoteAudio = document.querySelector('#remote-audio');
var localAudio = document.querySelector('#local-audio');
var peer = new Peer(peerID, {host: SERVER_IP, port: SERVER_PORT});
var conn = peer.connect(peerConnectionID);
var getUserMedia = navigator.mediaDevices.getUserMedia({ video: true, audio: true })
.then(stream => localAudio.srcObject = stream)
.then(stream => localVideo.srcObject = stream)
.then(stream => localStream = stream)
.catch(e => console.log(e.name + ": "+ e.message));
waitForElement();
function waitForElement(){
if(localStream != ""){
conn.on('open', function(){
conn.send('hi from android!');
});
peer.on('connection', function(conn) {
conn.on('data', function(data){
console.log(data);
});
});
peer.on('call', function(call) {
console.log("Picking up call.");
call.answer(localStream);
call.on('stream', function(remotestream) {
console.log("Call on.");
remoteVideo.srcObject = remotestream;
});
});
}
else{
setTimeout(function(){
waitForElement();
},750);
}
}
I think it is some little tweak that I'm getting wrong, I have mainly followed instructions on PeerJS website: http://peerjs.com/ Please if anyone can see something that needs to change, any help is welcome!
Are you using https? Making calls to non-local machines is no longer allowed by the browsers.
To test this out, run both sets of code on your local machine. If you can do that connection, it means your code is ok.
To do a remote connection you will unfortunately need https. This means you will also need your own peerjs server (to run as https).
The other option is to use port forwarding to make one of the machines think it is talking to the localhost
It sounds like your ICE Candidates cannot communicate one to each other. You will have to use a STUN server and, if it still doesnt work, you will need a TURN server.
From PeerJS Documentation:
var peer = new Peer({
config: {'iceServers': [
{ url: 'stun:stun.l.google.com:19302' },
{ url: 'turn:homeo#turn.bistri.com:80', credential: 'homeo' }
]} /* Sample servers, please use appropriate ones */
});
This link will provide you a method to deploy your own TURN server.