RabbitMQ: connect ECONNREFUSED error. Cant connect to the 5672 port - rabbitmq

I am trying to learn RabbitMQ. I am using the following code that I got from tutorials:
publisher.js:
const amqp = require("amqplib/callback_api");
amqp.connect(`amqp://localhost`, (err, connection) => {
if (err) throw err;
connection.createChannel((err, channel) => {
const queueName = 'queue';
const message = 'This is the message to send'
channel.assertQueue(queueName, {
durable:false,
});
channel.sendToQueue(queueName, Buffer.from(message));
console.log('Message: ' + message);
setTimeout(()=>{
connection.close();
}, 1000);
});
});
When I run publisher.js using node in the CLI, I get this error:
Error: connect ECONNREFUSED ::1:5672
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1300:16) {
errno: -61,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '::1',
port: 5672
}
I was expecting:
Console log with the message
Message should also be added to the queue
Is it a TCP connection or firewall issue? If so, how can I fix it?

Instead of localhost, use 127.0.0.1
That should fix the problem.

Related

How do I connect my database to local SQL Server Express using nose js

I am using Express framework and trying to connect to my SQL Server Express database locally. I am getting error - connection failure. I need help with that, if you'd please.
Steps completed so far..
npm install mssql
var sql = require("mssql");
// config for your database
var config = {
user: 'ImacamUser',
password: '*****',
server: 'localhost',
database: 'InvoicingData'
};
sql.connect(config, (err) => {
if (err) console.log(err);
// create Request object
var request = new sql.Request();
// query to the database and get the records
request.query('select * from Customers', function (err, recordset) {
if (err) console.log(err)
// send records as a response
res.send(recordset);
});
});
The error I get from this code is:
ConnectionError: Failed to connect to localhost:1433 - Could not connect (sequence)
at C:\Projects\RCN\Invoicing\node_modules\mssql\lib\tedious\connection-pool.js:70:17
at Connection.onConnect (C:\Projects\RCN\Invoicing\node_modules\tedious\lib\connection.js:1012:9)
at Object.onceWrapper (node:events:510:26)
at Connection.emit (node:events:390:28)
at Connection.emit (C:\Projects\RCN\Invoicing\node_modules\tedious\lib\connection.js:1040:18)
at Connection.socketError (C:\Projects\RCN\Invoicing\node_modules\tedious\lib\connection.js:1395:12)
at C:\Projects\RCN\Invoicing\node_modules\tedious\lib\connection.js:1176:14
at processTicksAndRejections (node:internal/process/task_queues:78:11) {
code: 'ESOCKET',
originalError: ConnectionError: Failed to connect to localhost:1433 - Could not connect (sequence)
at Connection.socketError (C:\Projects\RCN\Invoicing\node_modules\tedious\lib\connection.js:1395:28)
at C:\Projects\RCN\Invoicing\node_modules\tedious\lib\connection.js:1176:14
at processTicksAndRejections (node:internal/process/task_queues:78:11) {
code: 'ESOCKET',
isTransient: undefined
}
Any help would be appreciated.

Error: self-signed certificate When connecting to google FCM with XMPP protocol

I am trying to connect to google Firebase Messaging with xmpp protocol with Node Js with node-xmpp-client
But I am getting an TLS error
Below is the code:
const XMPP = require("node-xmpp-client");
config = {
id: "push-notify-xmpp",
key: "________KEY______",
port: "5236",
host: "fcm-xmpp.googleapis.com",
};
client = new XMPP.Client({
jid: `${config.id}#fcm-xmpp.googleapis.com`,
password: config.key,
port: config.port,
host: config.host,
legacySSL: true,
preferredSaslMechanism: "PLAIN",
});
client.connection.socket.on("error", function (error) {
console.log("socket error");
console.error(error);
process.exit(1);
});
client.on("online", function (data) {
console.log(
"Connected as " +
data.jid.local +
"#" +
data.jid.domain +
"/" +
data.jid.resource
);
});
client.on("error", function (err) {
console.log("server error");
console.error(err);
process.exit(1);
});
Error:
server error
Error: self-signed certificate
at TLSSocket.onConnectSecure (node:_tls_wrap:1538:34)
at TLSSocket.emit (node:events:513:28)
at TLSSocket._finishInit (node:_tls_wrap:952:8)
at ssl.onhandshakedone (node:_tls_wrap:733:12) {
code: 'DEPTH_ZERO_SELF_SIGNED_CERT'
}
Also tried the command :
NODE_TLS_REJECT_UNAUTHORIZED='0' node appServer.js
But above get an different error Unauthorised
Can Anyone have any Idea ow to deal with FCM server with XMPP

Netlify Apollo NextJS SSR Client network socket disconnected before secure TLS connection was established

I have an application I've built using NextJS that is hosted on Netlify. The API is hosted on Heroku (it's a NestJS project running GraphQL)
In local development mode, I have no problem with any of my SSR pages. However, in production, I continually get 500 errors that produce the following logs in the Netlify functions panel:
ERROR ApolloError: request to https://api.paladindeck.com/graphql failed, reason: Client network socket disconnected before secure TLS connection was established
at new ApolloError (/var/task/node_modules/#apollo/client/errors/errors.cjs:34:28)
at /var/task/node_modules/#apollo/client/core/core.cjs:1598:19
at both (/var/task/node_modules/#apollo/client/utilities/utilities.cjs:986:53)
at /var/task/node_modules/#apollo/client/utilities/utilities.cjs:979:72
at new Promise (<anonymous>)
at Object.then (/var/task/node_modules/#apollo/client/utilities/utilities.cjs:979:24)
at Object.error (/var/task/node_modules/#apollo/client/utilities/utilities.cjs:987:49)
at notifySubscription (/var/task/node_modules/zen-observable/lib/Observable.js:140:18)
at onNotify (/var/task/node_modules/zen-observable/lib/Observable.js:179:3)
at SubscriptionObserver.error (/var/task/node_modules/zen-observable/lib/Observable.js:240:7) {
graphQLErrors: [],
clientErrors: [],
networkError: FetchError: request to https://api.paladindeck.com/graphql failed, reason: Client network socket disconnected before secure TLS connection was established
at ClientRequest.<anonymous> (/var/task/node_modules/next/dist/compiled/node-fetch/index.js:1:64142)
at ClientRequest.emit (events.js:412:35)
at ClientRequest.emit (domain.js:475:12)
at TLSSocket.socketErrorListener (_http_client.js:475:9)
at TLSSocket.emit (events.js:400:28)
at TLSSocket.emit (domain.js:475:12)
at emitErrorNT (internal/streams/destroy.js:106:8)
at emitErrorCloseNT (internal/streams/destroy.js:74:3)
at processTicksAndRejections (internal/process/task_queues.js:82:21) {
type: 'system',
errno: 'ECONNRESET',
code: 'ECONNRESET'
},
extraInfo: undefined
}
I have attached Sentry to the application and it's capturing some similar information:
http
POST https://api.paladindeck.com/graphql [[undefined]]
Info
09:15:05
console
ApolloError: request to https://api.paladindeck.com/graphql failed, reason: Client network socket disconnected before secure TLS connection was established
at new ApolloError (/var/task/node_modules/#apollo/client/errors/errors.cjs:34:28)
at /var/task/node_modules/#apollo/client/core/core.cjs:1598:19
at both (/var/task/node_modules/#apollo/client/utilities/utilities.cjs:986:53)
at /var/task/node_modules/#apollo/client/utilities/utilities.cjs:979:72
at new Promise (<anonymous>)
at Object.then (/var/task/node_modules/#apollo/client/utilities/utilities.cjs:979:24)
at Object.error (/var/task/node_modules/#apollo/client/utilities/utilities.cjs:987:49)
at notifySubscription (/var/task/node_modules/zen-observable/lib/Observable.js:140:18)
at onNotify (/var/task/node_modules/zen-observable/lib/Observable.js:179:3)
at SubscriptionObserver.error (/var/task/node_modules/zen-observable/lib/Observable.js:240:7) {
graphQLErrors: [],
clientErrors: [],
networkError: FetchError: request to https://api.paladindeck.com/graphql failed, reason: Client network socket disconnected before secure TLS connection was established
at ClientRequest.<anonymous> (/var/task/node_modules/next/dist/compiled/node-fetch/index.js:1:64142)
at ClientRequest.emit (events.js:412:35)
at ClientRequest.emit (domain.js:475:12)
at TLSSocket.socketErrorListener (_http_client.js:475:9)
at TLSSocket.emit (events.js:400:28)
at TLSSocket.emit (domain.js:475:12)
at emitErrorNT (internal/streams/destroy.js:106:8)
at emitErrorCloseNT (internal/streams/destroy.js:74:3)
at processTicksAndRejections (internal/process/task_queues.js:82:21) {
type: 'system',
errno: 'ECONNRESET',
code: 'ECONNRESET'
},
extraInfo: undefined
}
Error
09:15:06
console
[GET] /_next/data/hHiW6IT3wpykwmCV9Cdhe/collections/d45ebedf-d7f1-4208-bfbf-e7aa1af43bd3/e54b8945-6ed0-4094-8c54-fbd42e755e97.json?cardInCollectionId=e54b8945-6ed0-4094-8c54-fbd42e755e97&collectionId=d45ebedf-d7f1-4208-bfbf-e7aa1af43bd3 (SSR)
Info
09:15:06
All of the other pages (which do not use SSR, but query the API) work as expected.
I have looked at other similar issues but none of the solutions have helped thus far.
When I'm unable to find a solution to an issue like this I tend to think I'm doing something very stupid and not realizing it. So, it's entirely possible I'm just missing something so basic I'm not even thinking about it.
Whew... that took me a few days.
So, it turns out this wasn't a simple thing to diagnose (at least, not for me).
The short answer to my problem was: Don't pass the context headers from getServerSideProps to the Apollo client. For some reason, those headers, even with the authorization header being appended, were causing something to break.
Here's what I'm doing now:
// graphql-client.ts
export class GraphQLClient {
private readonly logger = new Logger(GraphQLClient.name);
get value(): ApolloClient<NormalizedCacheObject> {
if (!this._client) {
this._client = this.createClient();
}
if (this._client === undefined)
throw new Error(`Error when creating graphql client`);
return this._client;
}
constructor(
private readonly user?: User | null,
private _client?: ApolloClient<NormalizedCacheObject>,
) {}
private createClient(): ApolloClient<NormalizedCacheObject> {
const isSsrMode = typeof window === 'undefined';
const httpLink = createHttpLink({ uri: apolloConfig.uri });
const authLink = setContext(async (_, context) => {
let token: string | undefined;
if (context?.headers?.cookie) {
try {
token = getCookie(TOKEN_COOKIE_NAME, context.headers.cookie);
} catch (err) {
this.logger.error(err);
token = await this.user?.getIdToken();
}
} else {
token = await this.user?.getIdToken();
}
const headers = {
// HERE IS HOW I FIXED THINGS
// If this is SSR, DO NOT PASS THE REQUEST HEADERS.
// Just send along the authorization headers.
// The **correct** headers will be supplied by the `getServerSideProps` invocation of the query.
...(!isSsrMode ? context.headers : []),
authorization: token ? `Bearer ${token}` : ``,
};
return { headers };
});
return new ApolloClient({
link: authLink.concat(httpLink),
credentials: 'include',
cache: new InMemoryCache({
possibleTypes: generatedIntrospection.possibleTypes,
}),
ssrMode: isSsrMode,
});
}
}
// mypage.tsx
...
...
...
export const getServerSideProps: GetServerSideProps = async (context) => {
if (!isCardDetailsPageQueryType(context.query))
return {
props: {},
};
const logger = new Logger(
`${CardDetailsPage.name}_${getServerSideProps.name}`,
);
const client = new GraphQLClient();
const GET_CARD_DETAILS_QUERY = gql`
// query
`;
const results = await client.value.query({
query: GET_CARD_DETAILS_QUERY,
variables: { id: context.query.cardInCollectionId },
context: {
headers: {
...context.req.headers, // <-- just pass the context headers, the client will automatically append the authorization header
},
},
});
const GET_OTHER_PRINTINGS_BY_NAME_QUERY = gql`
// query
`;
const otherPrintingResults = await client.value.query({
query: GET_OTHER_PRINTINGS_BY_NAME_QUERY,
variables: {
name: results.data.cardsInCollection.card.name,
collectionId: context.query.collectionId,
},
context: {
headers: {
...context.req.headers, // <-- same as above
},
},
});
return {
props: {
cardsInCollection: results.data.cardsInCollection,
otherPrintings: otherPrintingResults.data.otherPrintings,
allCardsInCollection: otherPrintingResults.data.allCardsInCollection,
},
};
};
This might be a very specific issue for my specific use case, but I do hope someone, someday, finds this helpful.

Error: Redis connection to 127.0.0.1:6379 failed - connect ECONNREFUSED

I will already setup npm, socket.io, redis and redis-server... but I can't understand this error:
throw er; // Unhandled 'error' event
^
Error: Redis connection to 127.0.0.1:6379 failed - connect ECONNREFUSED 127.0.0.
1:6379
at Object.exports._errnoException (util.js:1016:11)
at exports._exceptionWithHostPort (util.js:1039:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1138:14)
Code:
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var redis = require('redis');
server.listen(8890);
io.on('connection', function (socket) {
console.log("client connected");
var redisClient = redis.createClient();
redisClient.subscribe('message');
redisClient.on("message", function(channel, data) {
console.log("new message add in queue "+ data['message'] + " channel");
socket.emit(channel, data);
});
socket.on('disconnect', function() {
redisClient.quit();
});
});
redis.createClient() tries to connect to the local machine's redis server and try on the port number 6379. For this you need to start the redis server with the following command.
redis-server

How to authenticate rabbitmq in nodejs?

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;