Reference Error with module exports event discord.js - sql

I am very confused by this error. In my code I have /events/ and /commands/ this is in /events/ I made sure that everything else works but this I can't figure out. The code down below is meant to work as a server count for a website. Anybody know? Thank you.
const Discord = require('discord.js');
var db = require('mysql');
var con = db.createConnection({
host: "localhost",
user: "",
password: "",
database: ""
});
module.exports = (client, guildCreate) => {
//welcome embed
const welcomeEmbed = new Discord.MessageEmbed()
.setColor('#858884')
.setTitle('Hello!')
.setAuthor('DHL Bot', 'https://cdn.discordapp.com/app-icons/708717412391845988/967e1b05f7b8aeca1d6b4649dc5530c8.png')
.setDescription(`Hello I am DHL, I am devoloped by Den#0762. Please do !setup. For support you can join our support server https://discord.com/invite`)
.setTimestamp()
.setFooter('By: Den#0762', 'https://cdn.discordapp.com/avatars/407206318911258628/e972b589e0ea4c45064d39b0380d77fd.png')
guild.owner.send(welcomeEmbed)
//db for scount
con.connect(function(err) {
if (err) throw err;
var sql = "UPDATE scount SET servercount = servercount + 1";
con.query(sql, function (err, result) {
console.log(result.affectedRows + " new server");
});
});
}
(node:1949) UnhandledPromiseRejectionWarning: ReferenceError: guild is not defined
at module.exports (/root/dc/DHL/events/guildCreate.js:23:1)
at Client.emit (events.js:315:20)
at Object.module.exports [as GUILD_CREATE] (/root/node_modules/discord.js/src/client/websocket/handlers/GUILD_CREATE.js:33:14)
at WebSocketManager.handlePacket (/root/node_modules/discord.js/src/client/websocket/WebSocketManager.js:386:31)
at WebSocketShard.onPacket (/root/node_modules/discord.js/src/client/websocket/WebSocketShard.js:436:22)
at WebSocketShard.onMessage (/root/node_modules/discord.js/src/client/websocket/WebSocketShard.js:293:10)
at WebSocket.onMessage (/root/node_modules/ws/lib/event-target.js:125:16)
at WebSocket.emit (events.js:315:20)
at Receiver.receiverOnMessage (/root/node_modules/ws/lib/websocket.js:797:20)
at Receiver.emit (events.js:315:20)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:1949) 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:1949) [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.

You're referencing guild, but it isn't declared. Based on other code I've seen, I think you need something along these lines:
module.exports = (client, guildCreate) => {
//welcome embed
const welcomeEmbed = new Discord.MessageEmbed() [...]
client.on("guildCreate", guild => {
guild.owner.send(welcomeEmbed)
});
[...]

Related

Axios triggering weird in React native app

Hello i have a weird thing going on,im using axios in order to send post-get http request for my app.The thing is that axios in my pc working good but in my laptop need console.log("") before axios request i dont know why.This happens in all my files.
It gives me this error : Possible Unhandled Promise Rejection (id : 0 ):
[Axios error: Request failed with statis code 404]
Here is my code :
function getProfile(){
try{
//console.log("") <-------------------------- Here i put it
axios.post(URL+'/checkData',
{
usernameCheckAXIOS : username,
passwordCheckAXIOS : password,
})
.then((response)=>{
console.log(response.data)
setProfile(response.data);
if(response.data.responseOfProfile == false){
Alert.alert("Access Dinied")
}
else{
navigation.navigate('Home')
}
})
}catch(error){}
}
If you are getting a “Possible unhandled promise rejection” warning in your React Native app, it means that a promise was rejected, but the rejection was not handled. Promises in JavaScript are used to handle asynchronous operations, and they can either be resolved or rejected.
axios.post(URL+'/checkData',
{
usernameCheckAXIOS : username,
passwordCheckAXIOS : password,
})
.then((response)=>{
//... your code
})
.chatch(error => console.log(error)) // <-- add this line
The HTTP 404 Not Found response status code indicates that the server cannot find the requested resource
so verify your URL, should be invalid because it cannot be found.
[Axios error: Request failed with statis code 404] is an error URL not found.
Are you sure that the url URL+'/checkData' is valid ?

I can't run the node.js server using keystone.js framework

I have source code using keystone.js, and I can't run it because of a Mongodb connection error.
This is the code creating Keystone.
const keystone = new Keystone({
name: process.env.PROJECT_NAME,
adapter: new Adapter({dbName}),
mongo: 'mongodb://127.0.0.1:27017/',
sessionStore: new MongoStore({ url: 'mongodb://localhost/' }),
cookieSecret: 'process.env.COOKIE_SECRET',
appVersion: {
version: '1.0.0',
addVersionToHttpHeaders: false,
access: false,
},
cookie: {
secure: false,
maxAge: 1000 * 60 * 60 * 24 * 30, // 30 days
sameSite: false
}
});
...
await keystone.connect()
Here are the error details:
(node:9928) UnhandledPromiseRejectionWarning: Error: No MongoDB connection URI specified.
at resolveAllKeys (E:\Node.JS\frostbets-master-2-20210809T155720Z-001\frostbets-master-2\keystone\node_modules\#keystonejs\utils\dist\utils.cjs.dev.js:51:19)
at processTicksAndRejections (internal/process/task_queues.js:93:5)
at async Keystone.connect (E:\Node.JS\frostbets-master-2-20210809T155720Z-001\frostbets-master-2\keystone\node_modules\#keystonejs\keystone\lib\Keystone\index.js:450:5)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:9928) 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:9928) [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.
------------------------------------------------------------------------------------------
You haven't specified but it looks like you're on Keystone 5 so I'm going with that assumption.
There are a number of issue in the code you've posted:
The main problem you have is you're passing dbName to init you Adapter but you should be passing the full mongoUri.
That's the source of the specific error you're getting.
Pretty sure dbName was an option at one point but not in the current release of KS5.
Again, not sure which version you're actually on but if you've updated some packages in an older project, that might be it.
I'm not sure what the mongo key being passed in the Keystone config but I don't think it's valid.
Any config for Mongo (for the main DB) should be passed to the adapter.
The syntax you're using to create your MongoStore instance has been deprecated for the current version of that package.
If it works for you leave it, but in the code below I've used the more recent MongoStore.create() syntax.
In your code you have mongodb://127.0.0.1:27017/ (under the mongo key, which I think is ignored) and mongodb://localhost/ for the sessionStore.
For most systems this will refer to the same DB though it's not clear if that's intentional in your case.
In my code I've put the sessions in a separate DB (my-app-sessions) but that's optional.
Your config uses the literal string 'process.env.COOKIE_SECRET' as the cookie secret, not the value in the COOKIE_SECRET environment var.
This is almost certainly not what you want.
To solve these problems, you probably want something close to this:
const { Keystone } = require('#keystonejs/keystone');
const { GraphQLApp } = require('#keystonejs/app-graphql');
const { AdminUIApp } = require('#keystonejs/app-admin-ui');
const MongoStore = require('connect-mongo');
const { MongooseAdapter: Adapter } = require('#keystonejs/adapter-mongoose');
const keystone = new Keystone({
name: process.env.PROJECT_NAME,
adapter: new Adapter({ mongoUri: 'mongodb://localhost/my-app' }),
sessionStore: MongoStore.create({ mongoUrl: 'mongodb://localhost/my-app-sessions' }),
cookieSecret: process.env.COOKIE_SECRET,
appVersion: {
version: '1.0.0',
addVersionToHttpHeaders: false,
access: false,
},
cookie: {
secure: false,
maxAge: 1000 * 60 * 60 * 24 * 30, // 30 days
sameSite: false
}
});
// ...
module.exports = {
keystone,
apps: [new GraphQLApp(), new AdminUIApp({ name: process.env.PROJECT_NAME, enableDefaultRoute: true })],
};
In this code I've left the standard exports at the bottom rather than calling keystone.connect() directly so I can run it with yarn keystone dev.
Tested with..
"dependencies": {
"#keystonejs/adapter-mongoose": "^11.2.2",
"#keystonejs/app-admin-ui": "^7.5.2",
"#keystonejs/app-graphql": "^6.3.2",
"#keystonejs/keystone": "^19.3.3",
"connect-mongo": "^4.4.1"
}

discord.js [object Object]

First of yes i looked at other pages on hereabout object Object error, and of course they had no answers, so im trying to make a command that tells me how many people i have in my xp system (sql) and the number of people i would get it from would be from the id column in the xp table
so im getting [object Object] in my channel and no errors in console
this is the code im working with
module.exports.run = async(client, message, rows, con, result) => {
const Discord = require("discord.js");
var mysql = require('mysql');
var con = mysql.createConnection({
host: "remotemysql.com",
user: "oof",
port: "--",
password: "---",
database: "my peepee"
});
con.query("SELECT COUNT(*) AS id FROM xp", function (err, result) {
if (err) throw err;
message.channel.send(result);
}
)};
You are trying to convert an Object to a String, this will result in: [object Object]
Try to stringify the Object first like:
message.channel.send(require('util').inspect(result));
util is a node.js module thats included so no npm i util required

Loopback error - value is not an object

I am using loopback in backend. I am getting this error
Unhandled error for request POST /api/meetups/auth: Error: Value is not an object.
at errorNotAnObject (/Users/ankursharma/Documents/projects/meetupz/node_modules/strong-remoting/lib/types/object.js:80:13)
at Object.validate (/Users/ankursharma/Documents/projects/meetupz/node_modules/strong-remoting/lib/types/object.js:51:14)
at Object.fromTypedValue (/Users/ankursharma/Documents/projects/meetupz/node_modules/strong-remoting/lib/types/object.js:14:22)
at Object.fromSloppyValue (/Users/ankursharma/Documents/projects/meetupz/node_modules/strong-remoting/lib/types/object.js:41:17)
at HttpContext.buildArgs (/Users/ankursharma/Documents/projects/meetupz/node_modules/strong-remoting/lib/http-context.js:193:22)
at new HttpContext (/Users/ankursharma/Documents/projects/meetupz/node_modules/strong-remoting/lib/http-context.js:59:20)
at restStaticMethodHandler (/Users/ankursharma/Documents/projects/meetupz/node_modules/strong-remoting/lib/rest-adapter.js:457:15)
at Layer.handle [as handle_request] (/Users/ankursharma/Documents/projects/meetupz/node_modules/express/lib/router/layer.js:95:5)
at next (/Users/ankursharma/Documents/projects/meetupz/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/Users/ankursharma/Documents/projects/meetupz/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/Users/ankursharma/Documents/projects/meetupz/node_modules/express/lib/router/layer.js:95:5)
at /Users/ankursharma/Documents/projects/meetupz/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/Users/ankursharma/Documents/projects/meetupz/node_modules/express/lib/router/index.js:335:12)
at next (/Users/ankursharma/Documents/projects/meetupz/node_modules/express/lib/router/index.js:275:10)
at Function.handle
(/Users/ankursharma/Documents/projects/meetupz/node_modules/express/lib/router/index.js:174:3)
at router (/Users/ankursharma/Documents/projects/meetupz/node_modules/express/lib/router/index.js:47:12)
I have already searched stackoverflow, but I didnt find answer. Basically, i was trying to use body-parser . I went through one of the stackoverflow thread and implemented its solution. I was able to use body-parser successfully. So, that error has been solved. But, now this error is giving me tough time.
server.js file
'use strict';
var loopback = require('loopback');
var boot = require('loopback-boot');
var bodyParser = require('body-parser');
var multer = require('multer');
var app = module.exports = loopback();
//code for body parsing
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
//app.use(multer()); // for parsing multipart/form-data
//code for body parsing ends
app.start = function() {
// start the web server
return app.listen(function() {
app.emit('started');
var baseUrl = app.get('url').replace(/\/$/, '');
console.log('Web server listening at: %s', baseUrl);
if (app.get('loopback-component-explorer')) {
var explorerPath = app.get('loopback-component-explorer').mountPath;
console.log('Browse your REST API at %s%s', baseUrl, explorerPath);
}
});
};
// Bootstrap the application, configure models, datasources and middleware.
// Sub-apps like REST API are mounted via boot scripts.
boot(app, __dirname, function(err) {
if (err) throw err;
// start the server if `$ node server.js`
if (require.main === module)
app.start();
});
In middleware.json, I have updated parse property as well
"parse": {"body-parser#json": {},
"body-parser#urlencoded": {"params": { "extended": true }}},
For some reason, that error has gone. Not sure, may be it will come again. But now, this is the error, I am seeing
Unhandled error for request POST /api/meetups/auth: TypeError: cb is not a function
at Function.Meetups.auth (/Users/ankursharma/Documents/projects/meetupz/common/models/meetups.js:117:3)
at SharedMethod.invoke (/Users/ankursharma/Documents/projects/meetupz/node_modules/strong-remoting/lib/shared-method.js:270:25)
at HttpContext.invoke (/Users/ankursharma/Documents/projects/meetupz/node_modules/strong-remoting/lib/http-context.js:297:12)
at phaseInvoke (/Users/ankursharma/Documents/projects/meetupz/node_modules/strong-remoting/lib/remote-objects.js:677:9)
at runHandler (/Users/ankursharma/Documents/projects/meetupz/node_modules/strong-remoting/node_modules/loopback-phase/lib/phase.js:135:5)
at iterate (/Users/ankursharma/Documents/projects/meetupz/node_modules/strong-remoting/node_modules/loopback-phase/node_modules/async/lib/async.js:146:13)
at Object.async.eachSeries (/Users/ankursharma/Documents/projects/meetupz/node_modules/strong-remoting/node_modules/loopback-phase/node_modules/async/lib/async.js:162:9)
at runHandlers (/Users/ankursharma/Documents/projects/meetupz/node_modules/strong-remoting/node_modules/loopback-phase/lib/phase.js:144:13)
at iterate (/Users/ankursharma/Documents/projects/meetupz/node_modules/strong-remoting/node_modules/loopback-phase/node_modules/async/lib/async.js:146:13)
at /Users/ankursharma/Documents/projects/meetupz/node_modules/strong-remoting/node_modules/loopback-phase/node_modules/async/lib/async.js:157:25
at /Users/ankursharma/Documents/projects/meetupz/node_modules/strong-remoting/node_modules/loopback-phase/node_modules/async/lib/async.js:154:25
at execStack (/Users/ankursharma/Documents/projects/meetupz/node_modules/strong-remoting/lib/remote-objects.js:522:7)
at RemoteObjects.execHooks (/Users/ankursharma/Documents/projects/meetupz/node_modules/strong-remoting/lib/remote-objects.js:526:10)
at phaseBeforeInvoke (/Users/ankursharma/Documents/projects/meetupz/node_modules/strong-remoting/lib/remote-objects.js:673:10)
at runHandler (/Users/ankursharma/Documents/projects/meetupz/node_modules/strong-remoting/node_modules/loopback-phase/lib/phase.js:135:5)
at iterate (/Users/ankursharma/Documents/projects/meetupz/node_modules/strong-remoting/node_modules/loopback-phase/node_modules/async/lib/async.js:146:13)
check if your filters or your URL has black spaces i.e. %20, or anything wrong with the filter or url.
Loopback 3 makes a difference between array and object. You have to check your data type. See https://github.com/strongloop/strong-remoting/issues/360 for more information.
I was facing the same error but in my case it was due to a model property data length.The property was type object and a small dataLength which caused faulty record in my sql Model table.I have to Manually delete those faulty records and increase the dataLength of that property too.
Restart the app

Express server crashing due to MongoDB connection loss

I am having issues with an HTTP Node.js server built with:
Ubuntu 14.04
MongoDB 3.0.4
iojs v2.3.3
express=4.10.*
mongodb=1.4.34
The following middleware are being used:
app.use(response_time());
app.use(body_parser.urlencoded({extended: true}));
app.use(body_parser.json());
var MongoClient = require('mongodb').MongoClient;
app.use(function (req, res, next) {
var connection_options = {auto_reconnect: false};
MongoClient.connect(config.server.db, connection_options, function (err, db) {
if (err) {
log.error(err); // Logging error.
return next(err);
}
req.db = db;
next();
});
});
The server started running at 20:40:10 and successfully handled multiple requests.
At 02:59:02, the following error started to get logged on every request:
02:59:02.114Z ERROR CrowdStudy: failed to connect to [127.0.0.1:27017]
Error: failed to connect to [127.0.0.1:27017]
at null.<anonymous> (/home/ncphillips/Projects/crowdstudy/node_modules/mongodb/lib/mongodb/connection/server.js:555:74)
at emitThree (events.js:97:13)
at emit (events.js:175:7)
at null.<anonymous> (/home/ncphillips/Projects/crowdstudy/node_modules/mongodb/lib/mongodb/connection/connection_pool.js:156:15)
at emitTwo (events.js:87:13)
at emit (events.js:172:7)
at Socket.<anonymous> (/home/ncphillips/Projects/crowdstudy/node_modules/mongodb/lib/mongodb/connection/connection.js:534:10)
at emitOne (events.js:77:13)
at Socket.emit (events.js:169:7)
at emitErrorNT (net.js:1237:8)
My initial suspicion was that I was that the connection pool was filling up because I don't have anything to handle calling req.db.close(). I thought that passing in the options {auto_reconnect: false} would fix this issue by automatically closing the connection after some time, but it seems I was wrong.
Note that restarting the server fixes the issue, so I believe the problem has to do with Node rather than Mongo.
If this has to do with the connection pool, is there some setting I can pass to fix this, or can I have an end-ware that makes sure the connection always gets closed?
Thanks a lot to anyone who can help me out!
autoReconnect is an option that should be passed to the server configuration:
MongoClient.connect(config.server.db, {
server : { autoReconnect : false }
}, ...);
The documentation contains some errors: it states that the default setting is false (which it isn't), and it also states that autoReconnect should be set in an object called socketOptions (which it shouldn't).
You can add various event listeners to the db object that gets passed back, to detect when the connection to the database got closed/reconnected/...:
db.on('close', function(reason) { ... });
db.on('reconnect', function(db) { ... });
More events here.