I have created a cluster and would like to access it with MongoDB Compass.
Via Connect -> I have MongoDB Compass I get the following connection string:
mongodb+srv://myname:<password>#myname.nauqp.mongodb.net/dws
When I enter this string in MongoDB Compass and insert my password and replace test with the name of my DB, the connect button is disabled and the following error message below it:
querySrv ENOTFOUND _mongodb._tcp.myname.nauqp.mongodb.net
I also have the same problem when I want to establish the connection via mongoose. There I get the error message:
Error: querySrv ENOTFOUND _mongodb._tcp.myname.nauqp.mongodb.net
[nodemon] app crashed - waiting for file changes before starting ...
My config looks like this:
const connectDB = async () => {
try {
const connection = await mongoose.connect(process.env.MONGO_URI, {
useUnifiedTopology: true,
useNewUrlParser: true,
useCreateIndex: true,
})
} catch (error) {
// error handling
}
}
The MONGO_URI in my .env file looks like this:
mongodb+srv://myname:<password>#myname.nauqp.mongodb.net/dws?retryWrites=true&w=majority
MongoDB Compass Version: 1.22.1 (1.22.1)
Node Version: v14.15.0
What am I doing wrong?
It's the cluster's name after the #
mongodb+srv://myname:<password>#clustersname.nauqp.mongodb.net/dws?retryWrites=true&w=majority
Related
I want to make mqtt request to interact with my own broker . It should be done (client) using react or next.js and mqtt.js package.
I was attempt, but when I inspect a browser , It seems my browser attempt to ws connection and it currupt:
I was install this package :
npm i mqtt --save
Below are all stuffs which I attempt using these:
import React, { useEffect, useState } from "react";
import mqtt from "mqtt";
function Send() {
const [status, setStatus] = useState("Not Connect");
useEffect(() => {
//const client = mqtt.connect("wss://test.mosquitto.org:8081/mqtt");
const client = mqtt.connect("mqtt://171.22.25.40:1883");
client.on("connect", () => {
setStatus("Connect");
client.subscribe("IHS", (err) => {
if (!err) {
client.publish("IHS", "Test Message");
}
});
});
}, []);
return (
<div>
<p>{`Status: ${status}`}</p>
</div>
);
}
export default Send;
Is I missed an specific configuration for mqtt function ? How can I fix it?
Edit:
I append a configuration to mqtt variable like these snipped:
const options = {
port: 1883,
host: "171.22.25.40",
protocol: "mqtt",
keepalive: 10,
protocolId: "MQTT",
reconnectPeriod: 2000,
};
const client = mqtt.connect("mqtt://171.22.25.40:1883", options);
But nothing happened.
Edited:
I use this config in the mosquito config file, from C# can connect to mqtt but can't connect to wss
port 1883
listener 9001
protocol websockets
allow_anonymous true
You can not use native MQTT protocol from within the browser, because the browsers JavaScript sandbox will not allow you to make arbitrary TCP connections. You can only make HTTP or WS connections.
The MQTT.js package will always convert any mqtt:// URL to a ws:// when run in the browser.
You will need to make sure your broker is configured to accept MQTT over WebScoket connections and set the port number in the URL to match.
I am new to MERN development and I have been trying to add the username, email and password of a user to database but i get this error(when i try to add user after connecting to the database from thunderclient in json format in vscode):
[nodemon] 2.0.19
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node ./index.js`
Example app listening on port 3000
connected to mongodb successfully
{ name: 'kashish', email: 'mail#mail.com', password: '1234' }
/home/alien/codes/webDev/react/inotebook/backend/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js:151
const err = new MongooseError(message);
^
MongooseError: Operation `users.insertOne()` buffering timed out after 10000ms
at Timeout.<anonymous> (/home/alien/codes/webDev/react/inotebook/backend/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js:151:23)
at listOnTimeout (node:internal/timers:564:17)
at process.processTimers (node:internal/timers:507:7)
Node.js v18.7.0
[nodemon] app crashed - waiting for file changes before starting...
The code connects to the database successfully, but when i try to add the user (using thunder client before calling the api) it just shows me the given error here is the code which connects to the database and the one which saves data in database respectively:
const mongoose=require("mongoose")
const mongoUri="mongodb://localhost:27017"
const connectMongo=() => {
mongoose.connect(mongoUri,() => {
console.log("connected to mongodb successfully");
}).catch(error => handleError(error))
}
module.exports=connectMongo;
the code that adds user:
const express=require('express');
const User=require('../models/User');
const router=express.Router();
router.get('/',(req,res) => {
console.log(req.body);
const user=User(req.body);
user.save()
res.send(req.body);
})
module.exports=router;
I tried going through similar issues from the forum but i don't understand any of them, what am i missing?
another edit:
When i tried using async function and added await before user.save(), the response didn't occur, not sure if that is obvious but the user data shows up in console but there happens to be an error during saving data, is it possible that the timeout happens before the data can be saved? i am hosting mongodb on localhost so this is not an internet issue
here is the updated code for auth.js:
const express=require('express');
const User=require('../models/User');
const router=express.Router();
router.get('/',async (req,res) => {
console.log(req.body);
const user=User(req.body);
await user.save()
res.send(req.body);
})
module.exports=router;
updated code of db.js (connecting to database) with error handling:
const mongoose=require("mongoose")
const mongoUri="mongodb://localhost:27017"
const connectMongo=() => {
mongoose.connect(mongoUri).then(
() => console.log('connected')
).catch(e => console.log('error',e))
}
module.exports=connectMongo;
after the above update in code this shows up in a few mins:
Example app listening on port 3000
error MongooseServerSelectionError: connect ECONNREFUSED ::1:27017
at Connection.openUri (/home/alien/codes/webDev/react/inotebook/backend/node_modules/mongoose/lib/connection.js:824:32)
at /home/alien/codes/webDev/react/inotebook/backend/node_modules/mongoose/lib/index.js:380:10
at /home/alien/codes/webDev/react/inotebook/backend/node_modules/mongoose/lib/helpers/promiseOrCallback.js:41:5
at new Promise (<anonymous>)
at promiseOrCallback (/home/alien/codes/webDev/react/inotebook/backend/node_modules/mongoose/lib/helpers/promiseOrCallback.js:40:10)
at Mongoose._promiseOrCallback (/home/alien/codes/webDev/react/inotebook/backend/node_modules/mongoose/lib/index.js:1225:10)
at Mongoose.connect (/home/alien/codes/webDev/react/inotebook/backend/node_modules/mongoose/lib/index.js:379:20)
at connectMongo (/home/alien/codes/webDev/react/inotebook/backend/db.js:5:14)
at Object.<anonymous> (/home/alien/codes/webDev/react/inotebook/backend/index.js:3:1)
at Module._compile (node:internal/modules/cjs/loader:1120:14) {
reason: TopologyDescription {
type: 'Unknown',
servers: Map(1) { 'localhost:27017' => [ServerDescription] },
stale: false,
compatible: true,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
logicalSessionTimeoutMinutes: undefined
},
code: undefined
}
and before you ask, i already ran sudo systemctl start mongodb before starting the app. here is the output of sudo systemctl status mongodb:
● mongodb.service - MongoDB Database Server
Loaded: loaded (/usr/lib/systemd/system/mongodb.service; disabled; preset: disabled)
Active: active (running) since Mon 2022-08-22 14:59:01 IST; 24s ago
Docs: https://docs.mongodb.org/manual
Main PID: 5840 (mongod)
Memory: 163.0M
CPU: 857ms
CGroup: /system.slice/mongodb.service
└─5840 /usr/bin/mongod --config /etc/mongodb.conf
error MongooseServerSelectionError: connect ECONNREFUSED ::1:27017
This issue can occur when the MongoDB client is trying to connect to the MongoDB server over IPv6, but the server isn't actually listening on IPv6 (for whatever reason; I think that older versions of the server had to be told to listen on IPv6 but more recent versions should do so automatically, unless it's explicitly turned off).
To force the client to connect over IPv4, use the IPv4 localhost address:
const mongoUri="mongodb://127.0.0.1:27017"
I am trying to deploy my application to Heroku, the problem is when my application is trying to connect to the local SQL Server database doesn't work.
When i test my application on development environment everything works good, the connection to the localhost:1433 works correctly.
This is my DB config
const { Sequelize } = require('sequelize');
// Connection to SQL Server
const db = new Sequelize('Cafeteria', process.env.SQL_NAME, process.env.SQL_PASS, {
host: 'localhost',
dialect: 'mssql',
// logging: false,
});
module.exports = db;
Connection in server.js
// Connection to DB
async dbConnection() {
try {
await db.authenticate();
console.log('Database online');
} catch (error) {
throw new Error( error );
}
}
And this is the error on console (Heroku logs)
(node:21) UnhandledPromiseRejectionWarning: Error:
SequelizeConnectionError: Failed to connect to localhost:1433 - Could
not connect (sequence) at Server.dbConnection
(/app/models/server.js:43:19) at processTicksAndRejections
(internal/process/task_queues.js:93:5) at processTicksAndRejections
(internal/process/task_queues.js:80:21) { code: 'ESOCKET' }
Yes the TCP/IP is Enabled, the TCP Port is 1433, TCP Dynamic Ports are a blank space.
The SQL Server Browser is running.
I hope anyone can help me!
I am running a simple Vue app with webpack that I created with the vue-cli. When I run the dev server wtih npm run serve, it shows several errors in the client console when using sockjs-node. I believe this module is used by webpack for hot reloading (HMR).
The first error is:
Access to XMLHttpRequest at 'http://192.168.1.4:8080/sockjs-node/info?t=1615330207390' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I can solve this in two ways by editing the devServer in my vue.config.js. The first method is by setting public: 'localhost:8080'; and the second is by setting headers: {'Access-Control-Allow-Origin': 'http://192.168.1.4:8080', 'Access-Control-Allow-Credentials': 'true'}.
In both cases, I then see the following two errors:
POST http://localhost:8080/sockjs-node/690/qvgqwbdo/xhr_streaming?t=1615330686134 404 (Not Found)
GET http://localhost:8080/sockjs-node/690/zympwfsc/eventsource 404 (Not Found)
How do I resolve these errors so that the hot reloader will connect?
In the function I set to devServer.before in my vue.config.js file, I created my own websockets using Socket.io on the same port as my devSever. When the function returned, the devServer could not use that port for websockets, so it failed to launch sockjs-node. Therefore, when the frontend client tried to connect to the devServer, the requests were going to my sockets, instead of the devServer sockets, and it was ignoring them. Hence the 404 errors.
Here is my original code:
// server.js
const { createServer } = require('http')
const io = require('socket.io')
const addSocketEvents = require('./socket-api')
const port = process.env.PORT || 8080
module.exports = {
port,
configure(app) {
// `app` is an instance of express
// add the websockets
const httpServer = createServer(app)
socket = io(httpServer, {
path: '/socket-api'
})
addSocketEvents(socket)
// starts the server
// cannot use app.listen() because that will not start the websockets
httpServer.listen(port)
}
}
// vue.config.js
const { port, configure } = require('./server')
module.exports = {
devServer: {
before: configure,
public: `localhost:${port}`,
},
}
To fix this issue, I needed to allow the devServer to use the original port for sockjs-node, and launch my sockets on a different port. However, because I need to use the same port in production (due to restrictions by my current hosting provider), I only want my sockets to use a different port when running the devServer. To do this, I simply created a different httpServer and launched it on a different port, then created a proxy in the devServer config for that port. In my configure function, I just check to see if it is running in dev or prod, and act accordingly.
My production server is a simple express instance which calls the same configure function after it is created. This allows me to put all my startup code in one place.
Here is my new code:
// server.js
const { createServer } = require('http')
const io = require('socket.io')
const addSocketEvents = require('./socket-api')
const port = process.env.PORT || 8080
const proxyPort = 8081
module.exports = {
port,
proxyPort,
configure(app) {
// `app` is an instance of express
// add the websockets
let httpServer, socketPort
if (process.env.NODE_ENV === 'development') {
httpServer = createServer()
socketPort = proxyPort
} else {
httpServer = createServer(app)
socketPort = port
}
// adds the socket-api to be used via websockets
socket = io(httpServer, {
path: '/socket-api'
})
addSocketEvents(socket)
// starts the server
httpServer.listen(socketPort)
}
}
// vue.config.js
const { port, configure } = require('./server')
module.exports = {
devServer: {
before: configure,
public: `localhost:${port}`,
proxy: {
'/socket-api': {
target: `http://localhost:${proxyPort}`,
ws: true
}
}
},
}
Sometimes I refresh, and it works. Sometimes it just doesn't work.
I tried changing ganache GUI settings to use port 8545 which I read is the WebSockets port but it still won't connect. ws:127.0.0.1 won't work and neither will http://
This is my truffle config file. The rest of the code is large and won't help much.
// See <http://truffleframework.com/docs/advanced/configuration>
// #truffle/hdwallet-provider
// var HDWalletProvider = require("truffle-hdwallet-provider");
const path = require("path");
var HDWalletProvider = require("#truffle/hdwallet-provider");
module.exports = {
// See <http://truffleframework.com/docs/advanced/configuration>
// to customize your Truffle configuration!
// contracts_directory: "./allMyStuff/someStuff/theContractFolder",
contracts_build_directory: path.join(__dirname, "/_truffle/build/contracts"),
// migrations_directory: "./allMyStuff/someStuff/theMigrationsFolder",
networks: {
ganache: {
host: "127.0.0.1",
port: 7545,
//port: 8545,
network_id: 5777,
//network_id: "*", // Match any network id,
websockets: false, // websockets true breaks TODO: connection not open on send()
// wss
},
},
};
This is some of my code on the actual screen in question.
const options = {
web3: {
block: false,
fallback: {
type: 'ws',
//url: 'ws://127.0.0.1:8546',
url: 'http://127.0.0.1:7545',
},
},
contracts: [MyStringStore],
// polls: {
// accounts: IntervalInMilliseconds,
// },
events: {},
};
I don't understand why sometimes it works and I can see drizzle state and sometimes I can't. React native and web3 is very new to me.
I get errors like this:
00:06 Contract MyStringStore not found on network ID: undefined
Error fetching accounts:
00:06 connection not open
I am having real difficulty setting up drizzle as well. One thing I see is that your
url: 'http://127.0.0.1:7545',
For some reason Drizzle only works with 'ws' as the prefix for such a URL. I am trying to follow this guide by people who got it working.
I think websocket is only available in the command line version.
Try install and use ganache-cli instead of the gui version.