I created the bot with Botact packdge, it running, but I constantly have this error:
**
(node:5744) UnhandledPromiseRejectionWarning: TypeError: Cannot read property '0' of undefined
at executionItems.forEach (D:\Node\VK-sleep-bot\node_modules\botact\lib\utils\callbackHandler.js:7:35)
at Array.forEach (<anonymous>)
at module.exports (D:\Node\VK-sleep-bot\node_modules\botact\lib\utils\callbackHandler.js:4:18)
at api.then.catch.err (D:\Node\VK-sleep-bot\node_modules\botact\lib\utils\executeHandler.js:15:23)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:118:7)
(node:5744) 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(). (rejection id: 2)
**
Here my code:
const express = require('express');
const bp = require('body-parser');
const { Botact } = require('botact');
const app = express();
const bot = new Botact({
token: 'c70595eee2bcec797e2e18cb10eab81d46e3ffc68caea34e4d005f231af1c733c751c1ff9cd4908722591',
confirmation: '65a50ccd'})
bot.on(function(ctx){
console.log(ctx.body);
ctx.reply('Hello');
});
app.use(bp.json());
app.post('/', bot.listen);
app.listen(80);
Is anyone know, how I can fix it?
Related
I've created a topic in AWS SNS. Then I've created a subscription, in which an HTTP protocol is the endpoint .
I've written a simple script in express js to response to messages received from AWS-SNS.
The code expect to receive a json request. Then I'm trying to inspect the header of the request to decide on the appropriate response. If the header is SubscriptionConfirmation then the code will handle the request. And if the header is notification, it'll just print some message.
This is my code:
'use strict';
const express =require('express')
//const axios =require('axios')
//const got=require('got')
const request=require('request')
const app = express()
const bodyParser =require('body-parser')
const port = 4000
app.use(express.json())
// app.use(bodyParser.urlencoded({ extended: true }));
// app.use(bodyParser.json());
app.post('/', async function (req, res) {
try {
let valueStr = req.bod
let payload = JSON.parse(valueStr)
console.log(JSON.stringify(payload))
if (req.header('x-amz-sns-message-type') === 'SubscriptionConfirmation') {
const url = payload.SubscribeURL;
await request (url, handleSubscriptionResponse)
} else if (req.header('x-amz-sns-message-type') === 'Notification') {
console.log(payload)
//process data here
} else {
throw new Error(`Invalid message type ${payload.Type}`);
}
} catch (err) {
console.error(err)
res.status(500).send('Oops')
}
res.send('Ok')
})
var handleSubscriptionResponse = function (error, response) {
if (!error && response.statusCode == 200) {
console.log('Yess! We have accepted the confirmation from AWS');
}
else {
throw new Error(`Unable to subscribe to given URL`);
//console.error(error)
}
}
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
I've used ngrok to test my code. However, I've been getting some unexpected result when runing the script. The result shows some sort of errors which I'm not able to figure out:
Example app listening at http://localhost:4000
SyntaxError: Unexpected token u in JSON at position 0
at JSON.parse (<anonymous>)
at /home/ahmad/snstest/Sns.js:21:28
at Layer.handle [as handle_request] (/home/ahmad/snstest/node_modules/express/lib/router/layer.js:95:5)
at next (/home/ahmad/snstest/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/home/ahmad/snstest/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/home/ahmad/snstest/node_modules/express/lib/router/layer.js:95:5)
at /home/ahmad/snstest/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/home/ahmad/snstest/node_modules/express/lib/router/index.js:335:12)
at next (/home/ahmad/snstest/node_modules/express/lib/router/index.js:275:10)
at jsonParser (/home/ahmad/snstest/node_modules/body-parser/lib/types/json.js:119:7)
(node:36762) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:470:11)
at ServerResponse.header (/home/ahmad/snstest/node_modules/express/lib/response.js:771:10)
at ServerResponse.send (/home/ahmad/snstest/node_modules/express/lib/response.js:170:12)
at /home/ahmad/snstest/Sns.js:36:9
at Layer.handle [as handle_request] (/home/ahmad/snstest/node_modules/express/lib/router/layer.js:95:5)
at next (/home/ahmad/snstest/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/home/ahmad/snstest/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/home/ahmad/snstest/node_modules/express/lib/router/layer.js:95:5)
at /home/ahmad/snstest/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/home/ahmad/snstest/node_modules/express/lib/router/index.js:335:12)
(node:36762) 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(). (rejection id: 1)
(node:36762) [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'm a bit confused about the error !!3
I would appreciate any help on how to resolve this error.
I'm trying to do user authentification with passport and mongodb but I keep getting an error. I tried restarting the server and looking for places to put an await function but I believe I covered all my tracks. I'm still getting the error and I have no idea why. It might be in the database itself but I am not sure because I'm new to mongodb
the error:
app: authRouter MongoServerError: E11000 duplicate key error collection: mernpractice.users index: email_1 dup key: { email: null }
app: authRouter at C:\Users\Yanki XXIV\Desktop\pluralsight\node_modules\mongodb\lib\operations\insert.js:51:33
app: authRouter at C:\Users\Yanki XXIV\Desktop\pluralsight\node_modules\mongodb\lib\cmap\connection_pool.js:272:25
app: authRouter at handleOperationResult (C:\Users\Yanki XXIV\Desktop\pluralsight\node_modules\mongodb\lib\sdam\server.js:363:9)
app: authRouter at MessageStream.messageHandler (C:\Users\Yanki XXIV\Desktop\pluralsight\node_modules\mongodb\lib\cmap\connection.js:479:9)
app: authRouter at MessageStream.emit (events.js:400:28)
app: authRouter at processIncomingData (C:\Users\Yanki XXIV\Desktop\pluralsight\node_modules\mongodb\lib\cmap\message_stream.js:108:16)
app: authRouter at MessageStream._write (C:\Users\Yanki XXIV\Desktop\pluralsight\node_modules\mongodb\lib\cmap\message_stream.js:28:9)
app: authRouter at writeOrBuffer (internal/streams/writable.js:358:12)
app: authRouter at MessageStream.Writable.write (internal/streams/writable.js:303:10)
app: authRouter at TLSSocket.ondata (internal/streams/readable.js:726:22) +0ms
(node:484) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'close' of undefined
at addUser (C:\Users\Yanki XXIV\Desktop\pluralsight\src\routers\authRouter.js:29:16)
at processTicksAndRejections (internal/process/task_queues.js:95:5)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:484) 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:484) [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.
app: authRouter MongoServerError: E11000 duplicate key error collection: mernpractice.users index: email_1 dup key: { email: null }
app: authRouter at C:\Users\Yanki XXIV\Desktop\pluralsight\node_modules\mongodb\lib\operations\insert.js:51:33
app: authRouter at C:\Users\Yanki XXIV\Desktop\pluralsight\node_modules\mongodb\lib\cmap\connection_pool.js:272:25
app: authRouter at handleOperationResult (C:\Users\Yanki XXIV\Desktop\pluralsight\node_modules\mongodb\lib\sdam\server.js:363:9)
app: authRouter at MessageStream.messageHandler (C:\Users\Yanki XXIV\Desktop\pluralsight\node_modules\mongodb\lib\cmap\connection.js:479:9)
app: authRouter at MessageStream.emit (events.js:400:28)
app: authRouter at processIncomingData (C:\Users\Yanki XXIV\Desktop\pluralsight\node_modules\mongodb\lib\cmap\message_stream.js:108:16)
app: authRouter at MessageStream._write (C:\Users\Yanki XXIV\Desktop\pluralsight\node_modules\mongodb\lib\cmap\message_stream.js:28:9)
app: authRouter at writeOrBuffer (internal/streams/writable.js:358:12)
app: authRouter at MessageStream.Writable.write (internal/streams/writable.js:303:10)
app: authRouter at TLSSocket.ondata (internal/streams/readable.js:726:22) +9s
(node:484) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'close' of undefined
at addUser (C:\Users\Yanki XXIV\Desktop\pluralsight\src\routers\authRouter.js:29:16)
at processTicksAndRejections (internal/process/task_queues.js:95:5)
(node:484) 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)
auth.js
const express = require('express');
const debug = require('debug')('app: authRouter');
const { MongoClient } = require('mongodb');
const authRouter = express.Router();
authRouter.route('/signUp').post((req, res) => {
const {username, password} = req.body;
const url =
'mongodb+srv://Yoshi:Yumcmaster1#cluster0.atic5.mongodb.net?retryWrites=true&w=majority'
const dbName = 'mernpractice';
(async function addUser(){
let client
try {
let client = await MongoClient.connect(url);
const db = client.db(dbName);
const user = {username, password};
const results = await db.collection('users').insertOne(user);
debug(results);
req.login(results.ops[0], ()=> {
res.redirect('/auth/profile');
});
} catch (error) {
debug(error)
}
client.close();
}());
});
authRouter.route('/profile').get((req, res) => {
res.json(req.user);
})
module.exports = authRouter;
app.js
const express = require('express');
const chalk = require('chalk');
const debug = require('debug')('app');
const morgan = require('morgan');
const path = require('path');
const passport = require('passport');
const cookieParser = require('cookie-parser');
const session = require('express-session');
const PORT = process.env.PORT || 3000;
const app = express();
const sessionsRouter = require('./src/routers/sessionsRouter');
const adminRouter = require('./src/routers/adminRouter');
const authRouter = require('./src/routers/authRouter');
app.use(morgan('tiny'));
app.use(express.static(path.join(__dirname, '/public/')));
app.use(express.json());
app.use(express.urlencoded({extended: false}));
app.use(cookieparser());
app.use(session({secret: 'globomantics'}));
require('./src/config/passport.js')(app)
app.set('views', './src/views')
app.set('view engine', 'ejs')
app.use('/sessions', sessionsRouter);
app.use('/admin', adminRouter);
app.use('/auth', authRouter);
app.get('/', (req, res) => {
res.render('index', { title: 'Globomantics', data: ['a','b','c'] });
});
app.listen(PORT, () => {
debug(`listening on port ${chalk.green(PORT)}`);
});
the error "E11000 duplicate key error index: ..." is due to bad data in DB, you need to cleanup your data in collection mernpractice.users as there are multiple records with email missing/null and you have unique index on the email.
you can get all missing emails using query:
db.users.find({
email: {
$exists: false
}
})
or
db.collection.find({
email: null
})
you need to clean all documents with email null or set unique email for all such documents returned by query.
Also when you insert new record you need to ensure email is available otherwise it will insert first record with null but all subsequent inserts will try to insert email as null and throw same error.
pls refer to https://www.mongodb.com/community/forums/t/e11000-duplicate-key-error-collection/14141 and https://docs.mongodb.com/manual/core/index-unique/#unique-index-and-missing-field
For me, it was because I set a field say email in a schema to unique. I created a document and set the value of the email to 'exampleemail#example.com'. The problem occurred when I tried to create/update a new document whose value of an email is the same as the above.
Hi I've written the following route for an api endpoint which isn't working. When I test with Postman and my code, it's simply a 404 not found error.
router.patch("/favorite", async (req, res) => {
user = await User.findById(req.body.id)
if (user == null) {
return res.status(404).json({ message: 'Cannot find user' })
}
if (req.body.putArr != null) {
res.user.favPokemon = req.body.putArr;
}
try {
const updatedUser = await res.user.save();
console.log(res.user.favPokemon);
console.log(updateUser);
res.json(updatedUser);
} catch (err) {
res.status(400).json({ error: err.message });
}
});
What am I missing/what error do I have in my code? For reference, here's my mongoDB setup for users:
Edit: Apologies for not specifying the endpoint. To be more clear, the end point and code calling this is:
const favThis = async (e) => { // Patch method to favorite or unfavorite a pokemon
debugger;
e.preventDefault();
try {
console.log(putArr);
const newUser = {userID, putArr};
await axios.patch("http://localhost:5000/users/favorite", newUser);
} catch(err) {
err.response.data.msg && setError(err.response.data.msg)
}
};
, so it's http://localhost:5000/users/favorite. I have other endpoints working fine such as http://localhost:5000/users/login and http://localhost:5000/users/register, and inside server.js I have app.use("/users", require("./routes/users"));
Additionally, server.js is simply
const express = require("express");
const mongoose = require("mongoose");
const cors = require("cors");
require("dotenv").config();
// set up express
const app = express();
app.use(express.json());
app.use(cors());
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`The server has started on port: ${PORT}`));
// set up mongoose
mongoose.connect(
process.env.MONGODB_CONNECTION_STRING,
{
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
},
(err) => {
if (err) throw err;
console.log("MongoDB connection established");
}
);
// set up routes
app.use("/users", require("./routes/users"));
app.use("/todos", require("./routes/todo"));
Edit 2:: I notice now that when I test on Postman, it's an infinite loop and the call is hung. I also get the following warnings in my console:
(node:36447) 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)
and
(node:36447) [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.
Based on the warning you have failing code inside a promise which is not being caught. Perhaps in this line user = await User.findById(req.body.id).
Getting a UnhandledPromiseRejectionWarning when testing using mocha/chai
I am trying to create a web-application with node.js, mongoose and MongoDB,
I am trying to load the web-page localhost:8800/api/auth/register which is stuck at loading since past 15 minutes.
VS Code Terminal return the following :
(node:2908) UnhandledPromiseRejectionWarning: MongooseError: Operation `users.insertOne()` buffering timed out after 10000ms
at Timeout.<anonymous> (E:\Projects\Applications\chitter-chatter\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:185:20)
at listOnTimeout (internal/timers.js:554:17)
at processTimers (internal/timers.js:497:7)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:2908) 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: 3)
(node:2908) [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.
(node:2908) UnhandledPromiseRejectionWarning: MongooseError: Operation `users.insertOne()` buffering timed out after 10000ms
at Timeout.<anonymous> (E:\Projects\Applications\chitter-chatter\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:185:20)
at listOnTimeout (internal/timers.js:554:17)
at processTimers (internal/timers.js:497:7)
(node:2908) 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: 4)
My Scripts are as following :
Index.js :
const application = express();
const mongoose = require("mongoose");
const dotenv = require("dotenv");
const helmet = require("helmet");
const morgan = require("morgan");
const userRoute = require("./routes/users");
const authRoute = require("./routes/auth");
dotenv.config();
mongoose.connect(process.env.MONGO_URL, {useNewUrlParser: true, useUnifiedTopology: true}, () => {
console.log("connected to MongoDB")
});
// middleware
application.use(express.json());
application.use(helmet());
application.use(morgan("common"));
application.use("/api/users", userRoute);
application.use("/api/auth", authRoute);
application.listen(8800, () => {
console.log("backend server is running!")
})
Auth.js :
const User = require("../models/User");
// REGISTER
router.get("/register", async (req, res) => {
const user = await new User ({
username: "john",
useremail: "john#gmail.com",
userpswrd: "123456"
})
await user.save();
res.send("oK")
});
module.exports = router
I am also using .env for MONGO VIA URL CONNECTION
Sorry for the bad writing apologies in advance also I am new to this so pls correct me! I know i have done a lot of mistakes,
Thanks for u're sincere time dedication and sympathy
First of all, you must make sure that you are connecting to the database without any error.
To do this, start listening on connect's callback function:
try {
// This configuration is better
mongoose.connect(process.env.MONGO_URL, {
useUnifiedTopology: true,
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
}, err => {
if (err) throw Error(err.message);
console.log("connected to MongoDB");
application.listen(8800, () => console.log("backend server is running!"));
});
} catch (error) {
console.log(error);
}
I think you should make this operation in a try-catch statement like this:
// REGISTER
router.get("/register", async (req, res) => {
try {
// Create user in database
const user = await User.create({
username: "john",
useremail: "john#gmail.com",
userpswrd: "123456"
});
res.status(200).json({ success: true });
} catch (error) {
res.status(500).json({ error });
console.log(error);
}
});
module.exports = router;
Then you can see error's details, and server keeps running.
If you can't solve the problem just add a comment here I'll be back ASAP
check your router or wifi if you are using to run mongoose
try with your mobile internet
I am trying to connect to the Microsoft Azure CosmosDB Emulator in Node.js using mongoose. This is the code I am using:
var mongoose = require('mongoose');
mongoose.Promise = global.Promise;
mongoose.connect("mongodb://localhost:C2y6yDjf5%2FR%2Bob0N8A7Cgv30VRDJIWEHLM%2B4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw%2FJw%3D%3D#localhost:8081/cryptam?ssl=true");
This is the error I'm getting:
(node:6572) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): #<Object>
(node:6572) [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.
If I use this without url encoding, this is the error I get:
(node:8088) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): Error: Password contains an illegal unescaped character
(node:8088) [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, how do I fix this error to connect to my local Azure Cosmos DB emulator using Mongoose?
Try the following code,
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
const mongoUri = `mongodb://${process.env.COSMOSDB_ACCOUNT}:${process.env.COSMOSDB_KEY}#${
process.env.COSMOSDB_ACCOUNT
}.documents.azure.com:${process.env.COSMOSDB_PORT}/${process.env.COSMOSDB_DB}?ssl=true`;
// Local MongoDB Connection String
// const mongoUri = `mongodb://localhost:27017/connect-todoes`;
function connect() {
mongoose.set('debug', true);
return mongoose.connect(mongoUri, { useMongoClient: true });
}
module.exports = {
connect,
mongoose
};