enter image description here
I am not able to connect my database and getting this problem when i run any api call in postman ,I have tried so many things but not able to get it out .
This is probably because
The MongoDB service isn't started.
Start MongoDB: sudo systemctl start mongod
Verify that MongoDB has started successfully: sudo systemctl status mongod
The port is already serving some service.
Find pid: lsof -i:27017
Kill pid: kill -9 pid
Your connection string is incorrect
mongoose.connect('mongodb://localhost:27017/myapp');
Your localhost is not configured to use mongoDB
const app=require("./app");
const dotenv=require("dotenv");
const connectDatabase=require("./config/database");
PORT=4000;
//Handling uncaught Exception(YouTube Wala Error)
process.on("uncaughtException",(err)=>{
console.log(`Error:${err.message}`);
console.log(`Shuting Down the server due to uncaught Exception`);
process.exit(1);
})
// config
// dotenv.config({path:"backend/config/config.env"});
//Connecting to database
connectDatabase();
const server=app.listen(PORT,()=>{
console.log(`server is running on http://localhost:${PORT}`);
})
//Unhandled Promise Rejection-> in case when we use mongo(using)
process.on("unhandledRejection",err=>{
console.log(`Error: ${err.message}`);
console.log(`Shuting Down the server due to Unhandled Promise Rejection`);
server.close(() =>{
process.exit(1);
})
})
Related
On visiting local host 3000 I get Cannot GET / before using postman.
during the process of sending POST request in postman to the local host my program fails and I get this Error
`node:internal/process/promises:288
triggerUncaughtException(err, true /* fromPromise */);
^
Error: connect ECONNREFUSED ::1:5672
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1487:16) {
errno: -61,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '::1',
port: 5672`
config.js
----------
module.exports = {
rabbitMQ: {
url: "amqp://localhost",
exchangeName: "logExchange",
},
};
Producer.js
-----------
const amqp = require("amqplib");
const config = require("./config");
//step 1 : Connect to the rabbitmq server
//step 2 : Create a new channel on that connection
//step 3 : Create the exchange
//step 4 : Publish the message to the exchange with a routing key
class Producer {
channel;
async createChannel() {
const connection = await amqp.connect(config.rabbitMQ.url);
this.channel = await connection.createChannel();
}
async publishMessage(routingKey, message) {
if (!this.channel) {
await this.createChannel();
}
const exchangeName = config.rabbitMQ.exchangeName;
await this.channel.assertExchange(exchangeName, "direct");
const logDetails = {
logType: routingKey,
message: message,
dateTime: new Date(),
};
await this.channel.publish(
exchangeName,
routingKey,
Buffer.from(JSON.stringify(logDetails))
);
console.log(
`The new ${routingKey} log is sent to exchange ${exchangeName}`
);
}
}
module.exports = Producer;
Server.js
----------
`const express = require("express");
const bodyParser = require("body-parser");
const app = express();
const Producer = require("./producer");
const producer = new Producer();
app.use(bodyParser.json("application/json"));
app.post("/sendLog", async (req, res, next) => {
await producer.publishMessage(req.body.logType, req.body.message);
res.send();
});
app.listen(3000, () => {
console.log("Server started...");
});`
I am a Junior Intern ad was following along an youtube video by https://www.youtube.com/watch?v=igaVS0S1hA4 by Computerix to help me understand the concepts
I tried restarting the rabbitMQ and express server and running it on different ports but didnt solve the problem
This is Big Picture
Postman -> Express Server -> RabbitMQ -> node.js
#1 Postman send message to Express with Message Types and payload by POST call
#2 Express Server forward message to Rabbit MQ by publish
#3 RabbitMQ - push the messages into own message queue
#4 Each consumer received own message from RabbitMQ. It was binned before.
There are many complex options(order, priority) but in here talking about basic and simple model.
Steps
We needs following three steps.
#1 : Install
1.1 docker (easy way to container to run RabbitMQ)
1.2 node
1.3 demo source
git clone https://github.com/charbelh3/RabbitMQ-Logger-Example.git
File structure
1.4 install node library
At RabbitMQ-Logger-Example\infoMS directory
npm install amqplib
At RabbitMQ-Logger-Example\loggerMS directory
npm install amqplib express body-parser
At RabbitMQ-Logger-Example\warningAndErrorMS directory
npm install amqplib
1.5 Install Postman
1.6 Install Git Bash - I will using git bash terminal. It similar bash terminal in Linux - If you using Linux, skip this.
#2 : Binding
2.1 running RabbitMQ
Save this code as docker-compose.yml
version: "3.8"
services:
rabbitmq:
image: rabbitmq:management-alpine
container_name: 'rabbitmq'
ports:
- 5672:5672
- 15672:15672
volumes:
- ~/.docker-conf/rabbitmq/data/:/var/lib/rabbitmq/
- ~/.docker-conf/rabbitmq/log/:/var/log/rabbitmq
networks:
- rabbitmq_go_net
networks:
rabbitmq_go_net:
driver: bridge
Run it
docker compose up
If docker compose version 1.x
docker-compose up
Open your browser with this URL
http://localhost:15672/
2.2 Run express and all node.js
At RabbitMQ-Logger-Example\infoMS directory
node app.js
At RabbitMQ-Logger-Example\loggerMS directory
node server.js
At RabbitMQ-Logger-Example\warningAndErrorMS directory
node app.js
Now ready to go
#3 : Message
Run Postman,
#1 Make own collection
#2 Make Three requests
One of Request - Send Info Message
#1 Select POST method
#2 Enter URL
localhost:3000/sendLog
#3 Click Body Tab
#4 Select Raw radio button
#5 Enter message into body
{
"logType" : "Info",
"message" : "I am Info message"
}
#6 Select JSON
#7 Press Send Button
If you see , You are success!
Other two different type message is same content
Just difference is logType's value.
Send Warning Message Request
For Warning
{
"logType" : "Warning",
"message" : "I am Warning message"
}
Send Error Message Request
For Error
{
"logType" : "Error",
"message" : "I am Error message"
}
This is real screen all of things!
If you browser, RabbitMQ content, you found many things.
This is one of it for Info channel information.
If want to terminate RabbitMQ
CTRL+C
docker compose down
Enjoy RabbitMQ!
I'm starting at Node.js and i'm trying to make a simple connection with Sequelize based on its documentation (http://docs.sequelizejs.com/manual/installation/getting-started.html#installation).
Here my db.js file :
const Sequelize = require('sequelize')
const db = new Sequelize('chat','root','root',{
host: 'localhost',
port: 3306,
dialect: 'mysql'
});
db
.authenticate()
.then(() => {
console.log('Connection has been established successfully.');
})
.catch(err => {
console.error('Unable to connect to the database:', err);
});
When executing this code, I have no success nor error message, just a message indicating 'String base operators deprecated' but nothing important i think.
I tried changing localhost to 127.0.0.1, remove port number and multiples thread but i'm stucked here...
Tested your code and all seemed to work fine, it connected successfully to the database instance I have running.
You might want to ensure mysql2 package is installed. Also check that the database chat has been created in MySQL workbench, and ensure the password is correct.
I built mosquitto on CentOS7 and a node.js client based on mqtt.js,installing with
yum install mosquitto mosquitto-clients
The local test
> mosquitto_sub -h localhost -t test
> mosquitto_pub -h localhost -t test -m "hello world"
works fine, but when I ran:
var mqtt = require('mqtt')
var client = mqtt.connect('mqtt://192.168.1.70')
client.on('connect', function () {
client.subscribe('presence')
client.publish('presence', 'Hello mqtt')
})
client.on('message', function (topic, message) {
// message is Buffer
console.log(message.toString())
client.end()
})
I got Error: Connection refused: Not authorized
The mosquitto.conf is like:
pid_file /var/run/mosquitto.pid
persistence true
persistence_location /var/lib/mosquitto/
log_dest file /var/log/mosquitto/mosquitto.log
allow_anonymous true
and I use systemctl restart mosquitto to restart it several time, which doesn't help. The firewall is down and log file stays empty.
A screenshot on status:
Can anyone help please?
UPDATE:
It turns out that the mosquitto service is somehow broken as the status shows Active: active (exited).
I use mosquitto -p 1884 -v cmd to run another mosquitto process on port 1884, it works fine. Then I try to reload the conf using
> /etc/init.d/mosquitto reload. It gives me
Reloading mosquitto configuration (via systemctl): Job for mosquitto.service invalid.
[FAILED]
So there IS something wrong with mosquitto service.
Not a final solution but I manage to fix this by remove-reboot-install process, the status went green as follow:
SOLUTION
I managed to find out the reason it doesn't work. I've installed rabbitmq on my server, it uses its "rabbitmq_mqtt" which consumes port 1883. Reassigning a port will solve this problem.
I managed to find out the reason. I've installed rabbitmq on my server, it uses its "rabbitmq_mqtt" which consumes port 1883. Reassigning a port will solve this problem. The problem is simple, but yeah, the CLI should have given me more information.
You need to add the authorize information to mqtt connect method.Just like this.
var client=mqtt.connect("ws://192.168.1.1", {
username: "yourUsername",
password: "yourPassword"
}
Add the Authorization details for the client to connect
var mqtt = require('mqtt')
var client = mqtt.connect('mqtt://192.168.1.70', {
username: '<username>',
password: '<password>'
});
client.on('connect', function () {
client.subscribe('presence')
client.publish('presence', 'Hello mqtt')
})
client.on('message', function (topic, message) {
// message is Buffer
console.log(message.toString())
client.end()
})
I'm trying to establish a connection between my Meteor application and my MongoDB Atlas database.
I have the following bit of JavaScript:
var MongoClient = require('mongodb').MongoClient, format = require('util').format;
MongoClient.connect('<MyMongoURL>', function (err, db) {
if (err) {
throw err;
} else {
console.log("successfully connected to the database");
db.collection('largeTreeMap', function(err, docs) {
// Check for error
if(err) return console.log(err);
// Walk through the cursor
docs.find().each(function(err, doc) {
// Check for error
if(err) return console.err;
// Log document
console.log(doc);
})
});
}
db.close(); });
I added this to a blank JS document called test.js and upon running
node test.js
In my command line it returned the success message and data:
So now that I know the connection can be established I added the code to my Meteor project. I created a basic button and onClick the connection to MongoDB should completed.
However, instead I receive the following console error:
I understand from reading various Stack questions that this is a result of not running npm install mongodb in the project directory. However, I have tried doing this and the terminal returns:
Does any body know why the MongoDB is failing to install and preventing me from connecting to MongoDB in my application?
Any help would be much appreciated,
Many thanks,
G
You're trying to connect to the Mongo instance from the client, which is probably not what you want.
The mongodb npm package supports only Node.js, not JavaScript in the browser, as you can see from this line in its package.json
"engines": {
"node": ">=0.10.3"
},
In the case that worked, you are running it with Node.
What you probably want to do is to set the MONGO_URL environment variable to the Mongo Atlas instance, and leave the implementation of connecting / updating to Meteor itself.
Yosemite Mongo user working through a MEAN book. I've been following the steps exactly, but the MongoDB isn't connecting as expected. I installed Mongo once before to mess around with importing data, but didn't get too far. Below is all the Mongo related code I have besides package.json:
In app.js I have require('./app_server/models/db'); and in that folder I have:
var mongoose = require( 'mongoose' );
var dbURI = 'mongodb://localhost/Loc8r';
mongoose.connect(dbURI);
// CONNECTION EVENTS
mongoose.connection.on('connected', function () {
console.log('Mongoose connected to ' + dbURI);
});
mongoose.connection.on('error',function (err) {
console.log('Mongoose connection error: ' + err);
});
mongoose.connection.on('disconnected', function () {
console.log('Mongoose disconnected');
});
I am expecting to get
Express server listening on port 3000
Mongoose connected to mongodb://localhost/Loc8r
But instead get:
Mongoose disconnected
Mongoose connection error: Error: failed to connect to [localhost:27017]
I've tried changing a line to var dbURI = 'mongodb://localhost:3000/Loc8r'; because that's what my computer is using, but then get this error:
Mongoose disconnected
Mongoose connection error: Error: connection closed
Any help is much appreciated thanks.
Mongo was missing the folders it needed MongoDB not working. "ERROR: dbpath (/data/db) does not exist."
Then the server had to be run with "mongod"