how to implement rabbitmq in nodejs - rabbitmq

Error : TypeError: Cannot read property 'createChannel' of undefined
> Blockquote
Blockquote
var amqp = require('amqplib/callback_api');
amqp.connect('amqp://localhost', 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});
});
});
var amqp = require('amqplib/callback_api');
amqp.connect('amqp://localhost', function(err, conn) {
conn.createChannel(function(err, ch) {
var q = 'hello';
var msg = 'Hello World!';
ch.assertQueue(q, {durable: false});
// Note: on Node 6 Buffer.from(msg) should be used
ch.sendToQueue(q, new Buffer(msg));
console.log(" [x] Sent %s", msg);
});
});
TypeError: Cannot read property 'createChannel' of undefined
at D:\samadhan\Projects\RabbitMQ\sender.js:7:8
at D:\samadhan\Projects\RabbitMQ\node_modules\amqplib\callback_api.js:16:10
at Socket. (D:\samadhan\Projects\RabbitMQ\node_modules\amqplib\lib\connect.js:187:18)
at Object.onceWrapper (events.js:324:30)
at emitOne (events.js:125:13)
at Socket.emit (events.js:221:7)
at emitErrorNT (internal/streams/destroy.js:64:8)
at _combinedTickCallback (internal/process/next_tick.js:138:11)
at process._tickCallback (internal/process/next_tick.js:180:9)
D:\samadhan\Projects\RabbitMQ>enter code here

Related

React Native callback values cant set to state, got an error please help me to solve

React Native callback values cant set to state, got an error please help me to solve
//ERROR
//When callback values set to state i got an error
// WARN Possible Unhandled Promise Rejection (id: 0):
// TypeError: undefined is not an object (evaluating 'this.setState')
this.setState({Va_St_Data: cbDataResult.message});
let Va_Body = JSON.stringify({ cuscode: this.state.Va_St_UserCode, idno: this.state.Va_St_UserIDNo, password: this.state.Va_St_UserPassword });
Fun_Datafetch.call(this, Va_Body,"api/userlogin",function(cbDataResult) {
console.log('child : ' + cbDataResult.message);
//upto this line working fine
//output is : child : success/1
// Par : success/1
//*********** *
//ERROR
//When callback values set to state i got an error
// WARN Possible Unhandled Promise Rejection (id: 0):
// TypeError: undefined is not an object (evaluating
'this.setState')
this.setState({Va_St_Data: cbDataResult.message});
});
this.setState({Va_St_Loading: false });
};
export const Fun_Datafetch= (Va_Pa_Body, Va_Pa_UrlPart, callback) => {
try {
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
fetch(REACT_APP_ENV_DB_URL + Va_Pa_UrlPart, {method: "POST", headers: myHeaders, body: Va_Pa_Body, })
.then(response => response.json())
.then((result) => {callback(result);
console.log('Par : ' + result.message);
}).catch(function(error) {
callback(error);
//console.log('Error : ' + error);
});
} catch (error) {
callback(error);
//console.log('Error : ' + error);
}
}

What's the best way to create an LDAP connection to an OpenLDAP server using ldapjs?

I'm getting an error when attempting to create a client connection to an OpenLDAP server. The error message isn't helpful. Am I missing something in the OpenLDAP setup or configuration?
function createLDAPClient () {
return new Promise(function (resolve, reject) {
if(client.connected) return resolve();
client = ldap.createClient({
url: 'ldap://localhost:389',
strictDN: false,
timeout: 10000,
connectTimeout: 10000
//disableQueue: true
});
client.on('connect', function () {
// console.log("LDAP connected");
resolve();
});
client.on('error', function (err) {
// console.log("ldap client error", err);
// idle timeout
if(err.code === 'ECONNRESET') {
return reject();
}
reject();
});
});
}
Getting error
{ InvalidDnSyntaxError: invalid DN
at messageCallback (D:\Sites\Hermes\opt\node_modules\ldapjs\lib\client\client.js:1419:45)
at Parser.onMessage (D:\Sites\Hermes\opt\node_modules\ldapjs\lib\client\client.js:1089:14)
at Parser.emit (events.js:198:13)
at Parser.write (D:\Sites\Hermes\opt\node_modules\ldapjs\lib\messages\parser.js:111:8)
at Socket.onData (D:\Sites\Hermes\opt\node_modules\ldapjs\lib\client\client.js:1076:22)
at Socket.emit (events.js:198:13)
at addChunk (_stream_readable.js:288:12)
at readableAddChunk (_stream_readable.js:269:11)
at Socket.Readable.push (_stream_readable.js:224:10)
at TCP.onStreamRead [as onread] (internal/stream_base_commons.js:94:17) lde_message: 'invalid DN', lde_dn: null
}
The problem was eluding me because I didn't see where the error was being thrown. The answer is to solve the username in the bind function shown here:
function bind (user) {
return new Promise(function (resolve, reject) {
return createLDAPClient()
.then(function () {
//console.log("client should be bound", !client.unbound);
// client.bind(user.username, user.password, function (err) {
// console.log("attempting bind", user);
var ldapuser = user.username;
if( config.ldap.type == 'OpenLDAP'){
ldapuser = 'cn=' + user.username + ',' + config.ldap.dc;
}
client.bind(ldapuser, user.password, function (err) {
//console.log("user bind callback, err:", !!err);
if(err) {
// console.log("error type", typeof err, Object.keys(err), err.stack);
console.error(err);
// bad password
if(err.stack.indexOf("InvalidCredentialsError") !== -1) {
console.log("bad password", user);
reject({
msg: 'Invalid credentials - 101'
});
}
reject({
msg: 'Error connecting to LDAP server',
error: err
});
}
resolve();
});
});
});
}

Uncaught (in promise) TypeError: Cannot read property 'startsWith' of undefined

In my NuxtJS project, I cannot call my smart contract function inside a for loop. whenever I try to call outside of for loop it works well. What am I doing wrong?
let listOf = this.contract
const contractAddress = await this.cont.methods.contracts(2).call({
from: this.ethAddress
})
console.log("contract address in 2 index " + contractAddress) // it worrks
await this.contract.methods.getContractcount().call({
from: this.ethAddress
},
function (error, result) {
if (!error) {
var log = result
console.log(log)
var ContractList = async (log) => {
for (var i = 0; i < log; i++) {
console.log("==== " + i)
await listOf.methods.contracts(i).call({
from: this.ethAddress
})
.then(function (result) {
console.log(result) // it says error
});
}
}
ContractList(log)
} else {
console.log(error)
}
})
my console error
8d1bc033c0b40cc14af6.js:2 Uncaught (in promise) TypeError: Cannot read property 'startsWith' of undefined
at Function.t.fromHexString (8d1bc033c0b40cc14af6.js:2)
at t._callStaticAsync (8d1bc033c0b40cc14af6.js:2)
at t.<anonymous> (8d1bc033c0b40cc14af6.js:2)
at 8d1bc033c0b40cc14af6.js:2
at Object.next (8d1bc033c0b40cc14af6.js:2)
at 8d1bc033c0b40cc14af6.js:2
at new Promise (<anonymous>)
at Module.y (8d1bc033c0b40cc14af6.js:2)
at t._ethCall (8d1bc033c0b40cc14af6.js:2)
at t.<anonymous> (8d1bc033c0b40cc14af6.js:2)

Node/express endpoint - throwing unexpected error

I have an express endpoint that is throwing an unexpected error. I can't seem to figure out what is going on.
Here is the endpoint:
const express = require('express');
const bodyParser = require('body-parser');
const jsonParser = bodyParser.json();
const router = express.Router()
const { Article } = require('./model');
const passport = require('passport');
router.post('/highlight', jsonParser, (req, res) => {
const { removeId, addId } = req.body;
Article
.findByIdAndUpdate(removeId, {
featured: false
});
return Article
.findByIdAndUpdate(addId, {
featured: true
})
.then(article => {
res.status(202).json({ article });
})
.catch(err => {
res.status(404).json({ message: 'No record found' });
});
});
Here is the error:
SyntaxError: Unexpected token o in JSON at position 1
at JSON.parse (<anonymous>)
at parse (/Users/johnseabolt/Desktop/code/PERSONAL/dfpr/node_modules/body-parser/lib/types/json.js:89:19)
at /Users/johnseabolt/Desktop/code/PERSONAL/dfpr/node_modules/body-parser/lib/read.js:121:18
at invokeCallback (/Users/johnseabolt/Desktop/code/PERSONAL/dfpr/node_modules/raw-body/index.js:224:16)
at done (/Users/johnseabolt/Desktop/code/PERSONAL/dfpr/node_modules/raw-body/index.js:213:7)
at IncomingMessage.onEnd (/Users/johnseabolt/Desktop/code/PERSONAL/dfpr/node_modules/raw-body/index.js:273:7)
at emitNone (events.js:106:13)
at IncomingMessage.emit (events.js:208:7)
at endReadableNT (_stream_readable.js:1056:12)
at _combinedTickCallback (internal/process/next_tick.js:138:11)
at process._tickCallback (internal/process/next_tick.js:180:9)
I can't figure out what is happening here. It looked like it might be the jsonParser part, but I have another endpoint that has jsonParser and it works fine! Here is the working endpoint:
router.post('/create', jwtAuth, jsonParser, (req, res) => {
const { title, author, content } = req.body;
if (!title) {
return res.status(422).json({ message: 'Title is required' });
}
if (!author) {
return res.status(422).json({ message: 'Author is required' });
}
if (!content) {
return res.status(422).json({ message: 'Content is required' });
}
return Article
.create({ title, author, content })
.then(article => {
res.status(202).json({ article });
})
.catch(err => {
res.status(422).json({
error: err,
message: 'There was a problem with your request'
});
})
});
Can anyone see what's going on here? I've been stabbing at it for hours and I'm stumped.

How to publish a message to rabbitmq using Mocha framework

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