When I call the intent llamada the intent webhook triggers but it doesn't appear what I pass in the agent.add(json[0].name).
const express = require('express')
const app = express()
const {WebhookClient} = require('dialogflow-fulfillment');
const fetch = require('node-fetch')
let url = (ommited)
let settings = {method: "Get"};
app.get('/', function (req, res) {
res.send('Hello World')
})
app.post('/webhook', express.json() ,function (req, res) {
const agent = new WebhookClient({ request:req, response:res });
function llamada(agent) {
fetch (url, settings)
.then(res => res.json())
.then((json) => {
agent.add(json[0].name)
})
.catch((error) => {
assert.isNotOk(error,'Promise error');
});
}
let intentMap = new Map();
intentMap.set('llamada', llamada);
agent.handleRequest(intentMap);
})
app.listen(3000, () => {
});
I get this error:
ok
(node:9936) UnhandledPromiseRejectionWarning: Error: No responses defined for platform: DIALOGFLOW_CONSOLE
at V2Agent.sendResponses_ (C:\Users\aasensio\Desktop\Zerca\node_modules\dialogflow-fulfillment\src\v2-agent.js:243:13)
at WebhookClient.send_ (C:\Users\aasensio\Desktop\Zerca\node_modules\dialogflow-fulfillment\src\dialogflow-fulfillment.js:505:17)
at C:\Users\aasensio\Desktop\Zerca\node_modules\dialogflow-fulfillment\src\dialogflow-fulfillment.js:316:38
at processTicksAndRejections (internal/process/task_queues.js:93:5)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:9936) 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:9936) [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.
How can I make it to get in Dialogflow the response correctly?
The issue is that you're doing an asynchronous operation with a Promise, but agent.handleRequest() doesn't know to wait for the Promise to complete. So it tries to return a result to Dialogflow immediately, but the result hasn't been set yet.
In your case, addressing this is straightforward. You just need to return the Promise that is generated by the fetch().then()... chain. Something like this should work:
return fetch (url, settings)
.then(res => res.json())
.then((json) => {
agent.add(json[0].name)
})
.catch((error) => {
assert.isNotOk(error,'Promise error');
});
Related
(node:13384) UnhandledPromiseRejectionWarning: TypeError: cb is not a function
I am using passport js for authentication for my website, I am able to get all routes but when I try to sign up that is post router so in the console I am seeing these err, my data saved in DB but after posting my page loading continuously.
here these err what I am getting
(node:13384) UnhandledPromiseRejectionWarning: TypeError: cb is not a function
at C:\Users\SBCS\Desktop\AppBlog\node_modules\passport-local-mongoose\index.js:247:59
at processTicksAndRejections (internal/process/task_queues.js:93:5)
(Use node --trace-warnings ... to show where the warning was created)
(node:13384) 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:13384) [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 here is my post router code
app.post("/sign-up",(req,res)=>{
const username = req.body.username
const email = req.body.email
const password = req.body.password
User.register( {username:username}, req.body.email,req.body.password ,(err,user)=>{
if(err){
console.log(err);
res.redirect("/sign-up")
}else{
passport.authenticate("local" )(req,res, function (){
res.redirect('/compose')
})
}
})
and here is my mongoose connection
mongoose.connect('mongodb://localhost:27017/blog', {useNewUrlParser: true, useUnifiedTopology: true,useFindAndModify: false}).catch(err => console.log(err))
mongoose.set('useCreateIndex',true);
thanks
when I am getting err node js referring me this modules code see here
schema.statics.register = function(user, password, cb) {
// Create an instance of this in case user isn't already an instance
if (!(user instanceof this)) {
user = new this(user);
}
const promise = Promise.resolve()
.then(() => {
if (!user.get(options.usernameField)) {
throw new errors.MissingUsernameError(options.errorMessages.MissingUsernameError);
}
})
.then(() => this.findByUsername(user.get(options.usernameField)))
.then(existingUser => {
if (existingUser) {
throw new errors.UserExistsError(options.errorMessages.UserExistsError);
}
})
.then(() => user.setPassword(password))
.then(() => user.save());
if (!cb) {
return promise;
}
promise.then(result => cb(null, result)).catch(err => cb(err));
};
this is passport-local-mongoose module code
i got answer
this cause by
User.register( {username:username}, req.body.email,req.body.password ,(err,user)=>{
if(err){
line of code and after spending more time on it,I got some solution
solution is here
User.register({username: req.body.username}, req.body.password, function(err, user){
also if you want to send user name you can send it like this
User.register({username: req.body.username,name: req.body.registerName}, req.body.password, function(err, user){
thanks .....
i'm trying to make a rest api server with node express and mysql, the structure of the requests is this:
this is the route
router.get('/api/courseDetails/:id', async (req, res) => {
try {
let levels = await db.levelsByCourseId(req.params.id)
res.sendStatus(200).json(levels)
} catch (e) {
console.log(e)
res.sendStatus(500)
}
})
and this is the query:
requests.levelsByCourseId = (id) => {
let query = "select * from levels where parent_course_id="+id+" and visibility>0"
return new Promise((resolve, reject) => {
pool.query(query,(err, results) => {
if (err) {
return reject(err)
}
return resolve(results)
})
})
}
i use this structure also for other requests that works without errore, but this gives me this error:
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:485:11)
at ServerResponse.header (C:\Users\giuse\VScodeProjects\noderest-tutorial-server\node_modules\express\lib\response.js:771:10)
at ServerResponse.json (C:\Users\giuse\VScodeProjects\noderest-tutorial-server\node_modules\express\lib\response.js:264:10)
at C:\Users\giuse\VScodeProjects\noderest-tutorial-server\server\routes\index.js:47:29
at processTicksAndRejections (internal/process/task_queues.js:93:5) {
code: 'ERR_HTTP_HEADERS_SENT'
}
(node:15588) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:485:11)
at ServerResponse.header (C:\Users\giuse\VScodeProjects\noderest-tutorial-server\node_modules\express\lib\response.js:771:10)
at ServerResponse.contentType (C:\Users\giuse\VScodeProjects\noderest-tutorial-server\node_modules\express\lib\response.js:599:15)
at ServerResponse.sendStatus (C:\Users\giuse\VScodeProjects\noderest-tutorial-server\node_modules\express\lib\response.js:357:8)
at C:\Users\giuse\VScodeProjects\noderest-tutorial-server\server\routes\index.js:50:13
at processTicksAndRejections (internal/process/task_queues.js:93:5)
(node:15588) 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:15588) [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.
anyone could help me?
thank you
edit:
on the client side i have a promise and not some data (it is inside the promise)
Promise {<pending>}
__proto__: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: "OK"
and the axios code:
static async getCourseDetails(id) {
try {
const data = await axios.get(basepath + '/api/courseDetails/' + id)
return data.data
} catch (error) {
throw error;
}
}
You used wrong method to set status before sending results to a client.
It should be like this:
res.status(200).json(levels)
Calling setStatus you actually do res.status(200).send('OK') and right after that you call json that also sets status 200 and send a result as JSON.
The issue lies in the way you send the response. In the try block you await the levels from the db and then use sendStatus set a status and with json(levels) send a response as JSON back.
But according to the docs of Express.js sendStatus does the following.
res.sendStatus(200) // equivalent to res.status(200).send('OK')
So the status is being sent as a response. And after that you send another response as JSON. This is what triggers the error.
Use res.status(200) instead to only set the status without sending it.
router.get('/api/courseDetails/:id', async (req, res) => {
try {
let levels = await db.levelsByCourseId(req.params.id)
res.status(200).json(levels)
} catch (e) {
console.log(e)
res.sendStatus(500)
}
})
I am trying to run an async CMD command on with my Node server. Unfortunately my functions always throws an UnhandledPromiseRejectionWarning. I searched for results but never found a solution that fits my code.
(node:20704) UnhandledPromiseRejectionWarning: 0
(node:20704) 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:20704) [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 know that the error states I should use a catch block but I really dont know how I should implement that with the lambda implementation I used.
const exec = require('child_process');
const execWindowsCommand = new Promise(async (resolve, reject) => {
const process = exec.spawn('cmd', [ '/c', 'dir' ]);
process.on('data', data => resolve(data));
process.on('error', err => reject(err));
process.on('close', err => reject(err));
process.on('unhandledRejection', function(reason, promise) {console.log(promise);});
});
app.get("/cmdWIN", async(req, res) => {
execWindowsCommand()
.then(function(value) {
console.log(value);
res.send(value);
})
.catch((error) => {
console.error(error);
res.send(error);
});
});
I'm very new with NodeJS. I'm trying to create a simple server that has a connection to my mongoDB Atlas database but when I run my server I get this error:
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:8825) [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.
Seems to be a common problem based on what I googled, I added the try/catch but it still isn't working.
'use strict';
//const AWS = require('aws-sdk');
const express = require('express');
const mongoose = require('mongoose');
const uuidv4 = require('uuid/v4');
//exports.handler = (event, context, callback) => {
mongoose.connect(
'mongodb+srv://xxxx:xxxx#cluster0-us8bq.mongodb.net/test?retryWrites=true',
{
useNewUrlParser: true
}
),
() => {
try {
//something
} catch (error) {
console.error(error);
}
};
const connection = mongoose.connection;
connection.once('open', () => {
console.log('🖥 Connection to DB was succesful');
});
const app = express();
app.listen({ port: 4800 }, () =>
console.log(`🚀 Server ready at http://localhost:4800`)
);
Mongoose connect returns promise, and most probably there is an error when it attempts to connect: I would suggest using the async function, to handle DB connection. Here is what I use currently.
const config = require('config').db; // Your DB configuration
const combineDbURI = () => {
return `${config.base}${config.host}:${config.port}/${config.name}`;
};
// Connecting to the database
const connect = async function () {
const uri = combineDbURI(); // Will return DB URI
console.log(`Connecting to DB - uri: ${uri}`);
return mongoose.connect(uri, {useNewUrlParser: true});
};
And then call it within an async function using await:
(async () => {
try {
const connected = await connect();
} catch(e) {
console.log('Error happend while connecting to the DB: ', e.message)
}
})();
Or you can call without await using promise API:
connect().then(() => {
console.log('handle success here');
}).catch((e) => {
console.log('handle error here: ', e.message)
})
Besides, using try catch when using callbacks does not make sense, when you don't have promises, you should use error callbacks to catch errors.
So to answer your question (as others mentioned in the comments):
As connect function returns a promise, you should use catch callback to catch the promise rejection. Otherwise, it will throw Unhandled Promise Rejection.
I hope this will help.
UnhandledPromiseRejectionWarning means that promises should have .catch() like
mongoose.connect(...).catch(err => console.log(err))
Working with Node and mssql to pull queries for five different databases to de-dupe against each other and merge into a more unified schema.
My process follows this algorithm:
create a shared pool by calling this function:
const getPoolConnection = async () => {
try {
let pool = await mssql.connect(`mssql://${username}:${password}#${server}/`);
return pool;
} catch (err) {
console.error(err);
}
};
This function creates the pool and returns it to the calling function. username, password, and server are imported and scoped to this file.
Then we query each database and assign the result to a property on an object. This is accomplished via a forEach loop:
lists.forEach(list => {
fullData[list] = db.queryDatabase(pool, customers[list].query).catch(err => console.error(err));
})
which calls this function:
const queryDatabase = async (pool, query) => {
try {
let result = await pool.request().query(query);
// console.log(result);
return result.recordset, pool;
} catch (err) {
console.error(err);
}
};
now in order to keep post-processing from occuring before all database calls return data, I've wrapped the entire set of calls in a Promise.all() call in the main index.js file. This is the calling funciton:
const { customers } = require('./query');
const util = require('./util');
const db = require('./db');
fullData = {};
(async () => {
let pool = await db.getPoolConnection();
let lists = Object.keys(customers);
Promise.all(
lists.forEach(list => {
fullData[list] = db.queryDatabase(pool, customers[list].query).catch(err => console.error(err));
})
)
.then(results, pool => {
console.dir(results);
db.closePoolConnection(pool);
})
.catch(err => console.error(err));
})();
What I don't understand is this error that occurs when attempting to debug the application:
(node:18908) UnhandledPromiseRejectionWarning: TypeError: Cannot read
property 'Symbol(Symbol.iterator)' of undefined warning.js:18
at Function.all ()
at c:\Users\rutherfordc\Documents\GitHub\migration-plus\index.js:10:11
at
at process._tickCallback (internal/process/next_tick.js:188:7) (node:18908) 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) warning.js:18
(node:18908) [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. warning.js:18 (node:18908) UnhandledPromiseRejectionWarning:
ReferenceError: results is not defined warning.js:18
at c:\Users\rutherfordc\Documents\GitHub\migration-plus\index.js:15:11
at
at process._tickCallback (internal/process/next_tick.js:188:7) (node:18908) 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)
Promise.all() needs an array. So you could do something like this:
fullData = [];
(async () => {
let pool = await db.getPoolConnection();
let lists = Object.keys(customers);
lists.forEach(list => {
fullData.push(db.queryDatabase(pool, customers[list].query).catch(err => console.error(err));
}));
Promise.all(fullData)
.then((results, pool) => {
console.dir(results);
db.closePoolConnection(pool);
})
.catch(err => console.error(err));
})();
Update:
Also as J. Pichardo suggested in his answer, in case of multiple parameters, the parameters should be enclosed in parentheses.
Documentation
The error is non-logical but syntactical, the following lines in the main function
.then(results, pool => {
console.dir(results);
db.closePoolConnection(pool);
})
The arguments of the arrow function should be surrounded by parentheses, like:
.then((results, pool) => {
console.dir(results);
db.closePoolConnection(pool);
})
ReferenceError: results is not defined
So, the then is looking for a results variable and since it is an async function when it crashes it will be a UnhandledPromiseRejection.
Update:
As the other answer says Promise.all receives either multiple promises or an array of promises, so you could do something like:
var fullData = lists.map(list => db.queryDatabase(pool, customers[list].query).catch(err => console.error(err)));
Promise.all(fullData).then(...)