I am new to node.js and mongoDB Atlas. I am having an issue connecting to Mongo Atlas using the Node.js version 3.0 or later connection string.
const MongoDB = 'mongodb+srv://<user>:<password>#cluster0-nnezr.mongodb.net/<dbname>?retryWrites=true&w=majority'
When I use this connection string I get the following error -
MongoDB connection error: Error: querySrv ETIMEOUT _mongodb._tcp.cluster0-nnezr.mongodb.net
at QueryReqWrap.onresolve [as oncomplete] (dns.js:203:19) {
errno: undefined,
code: 'ETIMEOUT',
syscall: 'querySrv',
hostname: '_mongodb._tcp.cluster0-nnezr.mongodb.net'
}
(node:38809) UnhandledPromiseRejectionWarning: Error: querySrv ETIMEOUT _mongodb._tcp.cluster0-nnezr.mongodb.net
at QueryReqWrap.onresolve [as oncomplete] (dns.js:203:19)
(Use node --trace-warnings ... to show where the warning was created)
(node:38809) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside ofan async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:38809) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections thatare not handled will terminate the Node.js process with a non-zero exit code.
I have found a workaround using the previous connection string for node.js version 2.2.12 -
mongodb://<user>:<password>#cluster0-shard-00-00-nnezr.mongodb.net:27017,cluster0-shard-00-01-nnezr.mongodb.net:27017,cluster0-shard-00-02-nnezr.mongodb.net:27017/<dbname>?ssl=true&replicaSet=Cluster0-shard-0&authSource=admin&retryWrites=true&w=majority
When connecting I have to add {useUnifiedTopology: true}
mongoose.connect(mongoDB, { useNewUrlParser: true, useUnifiedTopology: true });
Can anyone give me a little insight on what im doing wrong with the new connection string?
Thanks!
have write user, password and maybe also database ,
const MongoDB = 'mongodb+srv://<user>:<password>#cluster0-nnezr.mongodb.net/<dbname>?retryWrites=true&w=majority'
user = your mongodb user name
password = your mongodb password
dbname = Database name
and don't forget to create a new user in MongoDB atlas.
Related
I am trying to send POST request from a NodeJs script to Python server (running with flask and waitress).
Most of the times the request is failed with the below error.
(node:42790) UnhandledPromiseRejectionWarning: Error: socket hang up
at connResetException (internal/errors.js:639:14)
at TLSSocket.socketOnEnd (_http_client.js:499:23)
at TLSSocket.emit (events.js:412:35)
at endReadableNT (internal/streams/readable.js:1334:12)
at processTicksAndRejections (internal/process/task_queues.js:82:21)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:42790) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
(node:42790) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
I am using NodeJs with axios package to send the request, and the configuration is as given below:
let axiosClient = axios.create({
timeOut: 300000,
maxContentLength: Infinity,
maxBodyLength: Infinity,
httpsAgent: new https.Agent({ keepAlive: true }),
httpAgent: new http.Agent({ keepAlive: true }),
});
let response = await axiosClient.post(end_point_url, data);
And when I checked in the server I could see that the 200 response is being sent, however in the client it is throwing an error.
My expectation is it should be successful in the first try, hence catching the error and retrying may not help in my case as most of the times it fails anyways.
Could you please guide in finding the root cause and fixing the same.
Thank you
let response = await axiosClient.post(end_point_url, data);
You should check end points correctly and use it in try and catch block
So I am trying to attach an image to a discord embed (preferably as the thumbnail). The image is locally stored on my hard drive. I am currently doing it this way:
attachment = await new discord.MessageAttachment('serverFavicon.png', 'favicon.png');
embed.setThumbnail(attachment);
and this returns this error and not send the embed:
(node:60598) UnhandledPromiseRejectionWarning: DiscordAPIError: Invalid Form Body
embed.thumbnail.url: Could not interpret "{'attachment': 'serverFavicon.png', 'name': 'favicon.png'}" as string.
at RequestHandler.execute (/Users/manders/Desktop/Bots/Minecraft Server Discord Bot/node_modules/discord.js/src/rest/RequestHandler.js:154:13)
at processTicksAndRejections (internal/process/task_queues.js:93:5)
at async RequestHandler.push (/Users/manders/Desktop/Bots/Minecraft Server Discord Bot/node_modules/discord.js/src/rest/RequestHandler.js:39:14)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:60598) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:60598) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
The strange thing is if I do
message.channel.send('Image', attachment);
It will successfully send the image.
So I am wondering why it won't attach to the embed, but it can send to a channel.
setThumbnail only accepts a string (the URL of the image), not a MessageAttachment.
In your example, you can simply use the URL of the image:
embed.setThumbnail('serverFavicon.png');
If you want to rename the image, you can attach the MessageAttachment when sending the message and use attachment://image-name.png for the thumbnail URL:
// You also don't need to use await here; constructors can't be async
const attachment = new discord.MessageAttachment('serverFavicon.png', 'favicon.png');
embed.setThumbnail('attachment://favicon.png');
// ...
// Discord.js v12:
message.channel.send({embed, files: [attachment]});
// Discord.js v13:
message.channel.send({embeds: [embed], files: [attachment]});
See the Discord developer docs for more information on using attachments in embeds.
Hi I'm new in javascript, I try to post url-encoded Api from lala.ai. I,m followed the instructions from the internet but still got an error. below I put the code and results.
//This is the instruction
POST /api/preview/
Puts a file in the preview queue (the first minute of vocals).
Parameters (form-urlencoded):
id (str): File id obtained from /upload/ method.
filter_type (int, optional): Number of postprocess iterations with MWF.
webpush-callback (json, optional): Client data for sending push notifications.
Returns (json):
{
"status": "success" | "error"
"error": Error description if the status is "error"
}
Examples:
$ curl --url https://www.lalal.ai/api/preview/ --form-string "id=9a3ae258-7693-4046-87c2-ef577eb752bb" --form-string "filter_type=2"
{"status": "success"}
$ curl --url https://www.lalal.ai/api/preview/
{"status": "error", "error": "No file id"}
This is what I have tried
const qs = require("qs");
axios
.post(
"https://www.lalal.ai/api/preview/",
{
data: qs.stringify({
id: "4d2f9262-e578-4290-97d3-43303fffbf56",
filter_type: "2",
}),
},
{
headers: {
"content-type": "application/x-www-form-urlencoded;charset=utf-8",
},
}
)
.then((result) => {
console.log(result);
});
This the error result I got
(node:34480) UnhandledPromiseRejectionWarning: Error: Request failed with status code 403
at createError (D:\reactjs\upload_lalal\server\node_modules\axios\lib\core\createError.js:16:15)
at settle (D:\reactjs\upload_lalal\server\node_modules\axios\lib\core\settle.js:17:12)
at IncomingMessage.handleStreamEnd (D:\reactjs\upload_lalal\server\node_modules\axios\lib\adapters\http.js:244:11)
at IncomingMessage.emit (events.js:327:22)
at endReadableNT (_stream_readable.js:1327:12)
at processTicksAndRejections (internal/process/task_queues.js:80:21)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:34480) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
(node:34480) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Can someone explain to me why that is error and how to fix it? Thanks.
Your error is... HTTP 403, which means
The HTTP 403 is a HTTP status code meaning access to the requested resource is forbidden
Do you need an access token to use the API?
So I am just gettting into web dev and as i've been following along with colt steele's course on udemy. The class is going swell and I am building my own website on the side which I am trying to host on a raspberry pi 4 (I have a 32 bit version as well as the new 64 bit version). I have the web app and database working fine locally on my win10 laptop, but I cannot get the app to work on my pi. I am using Node v12.18.3, express v4.17.1, and mongodb v4.4 (shell and server, win10 machine), and mongodb v2.4.14(raspberry pi).
the problem I seem to be having is connecting to the mongo database. I think this is cause I'm using mongoose to try to connect to mongodb but mongoose wont support mongodb version 2.4.14.
this is my code that works on my win 10 machine to connect:
mongoose.connect('mongodb://localhost:27017/Fries-and-Ketchup', { useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false });
mongoose.connection.on('connected', () => {
console.log('connected to mongoDB');
});
mongoose.connection.on('error' , err => {
console.log('error connecting to mongodb');
});
this is the error i get in my terminal:
(node:31771) UnhandledPromiseRejectionWarning: MongoServerSelectionError: Server at localhost:27017 reports maximum wire version 0, but this version of the Node.js Driver requires at least 2 (MongoDB 2.6)
at Timeout._onTimeout (/home/pi/Fries_and_ketchup/node_modules/mongodb/lib/core/sdam/topology.js:438:30)
at listOnTimeout (internal/timers.js:549:17)
at processTimers (internal/timers.js:492:7)
(node:31771) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:31771) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
so I tried using a different piece of code I found but unfortunately this doesnt work either:
const MongoClient = require("mongodb").MongoClient;
const url = "mongodb://10.0.0.109:27017";
MongoClient.connect("mongodb://localhost:27017/Fries-and-ketchup", {
useNewUrlParser: true,
useUnifiedTopology: true
})
how can I connect to the Mongo database on the Pi?
Try
const {MongoClient} = require('mongodb');
const url = "mongodb://127.0.0.1:27017/Fries-and-ketchup";
const client = new MongoClient.connect(url, { useNewUrlParser: true, useUnifiedTopology: true });
Since MongoClient is a class, you need to declare it with new
you are doing it rigth, but please check your mongodb version with :
mongo --version
if this version is < 3.1.0 update your mongo version to => 3.1.0 and use this connection code:
MongoClient.connect("mongodb://localhost:27017/Fries-and-ketchup", {
useNewUrlParser: true,
useUnifiedTopology: true
})
or even use mongoose driver, if you want to keep your actual mongo db version(2.x.x), try to connect like this:
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/Fries-and-ketchup', function(err, db) {console.log("connect",db)});
I'm learning Sails JS (and NodeJS), and I'm trying to set a connection to SQL Server Express. What I have so far:
A database called test-project-db with a table inside called TestTable1. It has two columns: name varchar(20) and description varchar(100).
A sails project generated with sails new, and a model/component made with sails generate api TestTable1.
My files:
- api/models/TestTable1.js
module.exports = {
attributes: {
name: {
type: 'string',
},
description: {
type: 'string',
},
}
};
- config/connections.js:
sqlserver: {
adapter : 'sails-sqlserver',
user : 'sa',
password: 'passw',
host : 'localhost\\SQLEXPRESS',
database: 'test-project-db'
}
- config/models.js:
module.exports.models = {
connection: 'sqlserver',
migrate: 'safe',
};
But when I run the server with sails lift and go to localhost:1337/testtable1, I get the error:
(node:15756) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): ConnectionError: Failed to connect to localhost:undefined in 60000ms
(node:15756) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
And, if instead of sails-sqlserver I use sails-mssqlserver, I get (in the console):
{"name":"Sails-MSSqlserver","hostname":"DESKTOP-PMN0K03","pid":15928,"level":30,"msg":"Error in __FIND__: { ConnectionError: Failed to connect to localhost:undefined in 60000ms\n at Connection.<anonymous> (D:\\Práctica 2\\test-project\\node_modules\\sails-mssqlserver\\node_modules\\mssql\\lib\\tedious.js:378:25)\n at Object.onceWrapper (events.js:315:30)\n at emitOne (events.js:116:13)\n at Connection.emit (events.js:211:7)\n at Connection.connectTimeout
(D:\\Práctica 2\\test-project\\node_modules\\sails-mssqlserver\\node_modules\\tedious\\lib\\connection.js:467:12)\n at ontimeout (timers.js:475:11)\n at tryOnTimeout (timers.js:310:5)\n at Timer.listOnTimeout (timers.js:270:5)\n name: 'ConnectionError',\n message: 'Failed to connect to localhost:undefined in 60000ms',\n code: 'ETIMEOUT' }","time":"2018-01-31T19:00:27.325Z","v":0}
error: Sending 500 ("Server Error") response:
Error (E_UNKNOWN) :: Encountered an unexpected error
ConnectionError: Failed to connect to localhost:undefined in 60000ms
at Connection.<anonymous> (D:\Práctica 2\test-project\node_modules\sails-mssqlserver\node_modules\mssql\lib\tedious.js:378:25)
at Object.onceWrapper (events.js:315:30)
at emitOne (events.js:116:13)
at Connection.emit (events.js:211:7)
at Connection.connectTimeout (D:\Práctica 2\test-project\node_modules\sails-mssqlserver\node_modules\tedious\lib\connection.js:467:12)
at ontimeout (timers.js:475:11)
at tryOnTimeout (timers.js:310:5)
at Timer.listOnTimeout (timers.js:270:5)
Details: ConnectionError: Failed to connect to localhost:undefined in 60000ms
And in the browser:
[Error (E_UNKNOWN) Encountered an unexpected error] Details: ConnectionError: Failed to connect to localhost:undefined in 60000ms
Along a 500 error page.
Any idea on what am I doing wrong?
localhost:undefined --> The port is undefined because you didn't provide it in the configuration. Add in the port attribute into your sqlserver connection within config/connections.js, and assign it your database server's port.
Side note: learning Sails while learning Node is quite a handful, especially since Sails can look intimidating at first. Just take it piece by piece, and you'll definitely get a hang of it. If you're familiar with MVC frameworks, such as Rails, then Sails will feel right at home.