I can not send an email to the mail - javascript

I can’t send email to. When registering, you must send a letter to the mail to confirm it.
I get an error: Callback must be a function at maybeCallback
const fs = require('fs');
const path = require('path');
let path_file = path.join(__dirname, '/views/email_templates/confirm_email.html');
let html_file = await fs.readFile(path_file, { encoding: 'utf-8' });
let html = await html_file(path_file);
let template = handlebars.compile(html);
let replacements = {
target_link: link,
password: merchant_password,
};
let htmlToSend = template(replacements);
let mailOptions = {
from: config.transport.user,
to : merchant_email,
subject : 'Please confirm your Email account and login password',
html : htmlToSend,
};
smtpTransport.sendMail(mailOptions);
What's my mistake?
(node:14300) UnhandledPromiseRejectionWarning: TypeError [ERR_INVALID_CALLBACK]: Callback must be a function
at maybeCallback (fs.js:128:9)
at Object.readFile (fs.js:277:14)
at readFile (C:\Users\User\Documents\backend\src\controllers/merchants.js:299:38)
at process._tickCallback (internal/process/next_tick.js:68:7)
(node:14300) 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:14300) [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.

fs.readFileSync(...)
Try using a synchronous way for reading the file.

Error is pretty much clear. you must pass callback function to send method
smtpTransport.sendMail(mailOptions, function (error, info) {
if (error) {
console.log('error occurred while sending');
console.log(error);
return;
}
console.log('Message sent:');
});

Related

TypeError: cb is not a function in nodejs?

(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 .....

Unhandled promise rejection nodejs

I am trying to use openweather-apis to connect to a dialogflow agent. I am new to promises and I keep getting the warning UnhandledPromiseRejectionWarning and I'm not sure on how to fix this.
Currently I have 2 files weather.js, which makes the api call
const api = require("openweather-apis")
api.setAPPID(process.env.API_KEY)
api.setUnits("metric")
module.exports = {
setCity: function(city) {
api.setCity(city)
},
getWeather: function() {
return new Promise(function(resolve, reject) {
api.getTemperature(function(err, temp) {
if (err) reject(err)
resolve(temp)
})
})
}
}
And I make use of weatherinCity.js, which retrieves the city from the agent, calls the calling function and then sends a response to the user.
const weather = require("../../weather")
module.exports = {
fulfillment: function(agent) {
const city = agent.parameters.geo_city
weather.setCity(city)
weather.getWeather().then(function(temp) {
agent.add(
"It is ${temp} degrees Celcius in ${city}"
)
}).catch(() => {
console.error("Something went wrong")
})
}
}
full error message:
(node:2896) UnhandledPromiseRejectionWarning: Error: No responses defined for platform: DIALOGFLOW_CONSOLE
at V2Agent.sendResponses_ (C:\Users\Coen\Desktop\ciphix-ca-case\node_modules\dialogflow-fulfillment\src\v2-agent.js:243:13)
at WebhookClient.send_ (C:\Users\Coen\Desktop\ciphix-ca-case\node_modules\dialogflow-fulfillment\src\dialogflow-fulfillment.js:505:17)
at C:\Users\Coen\Desktop\ciphix-ca-case\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:2896) 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:2896) [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.
This error indeed happened because this code fails to handle the Promise Rejection. While I'm not sure which Promise Rejection that failed to handle, but based on this and this GitHub discussions. It seems you need to return the agent.add() function.
I recommend trying async-await style with the consequence that you have to add a try catch block
module.exports = {
fulfillment: async function(agent) {
try {
const city = agent.parameters.geo_city
weather.setCity(city)
let temp = await weather.getWeather()
agent.add(
"It is ${temp} degrees Celcius in ${city}"
)
} catch (err) {
console.error("Something went wrong")
console.error(err)
}
}
}
Every error that is thrown on the try block should be caught in a catch block. Don't forget to add async before the function.
it will not solve your problem but generally speaking, i would add "return" after if(err). because otherwise the call to resolve would be done. in your particular case it will do no harm, as because of the nature of promises it will be ignored. but if you had written anything between reject and resolve it would have been executed.
// best practice
if (err) return reject(err)
for your problem, i've just tried this fast test to convice myself that even throws are catched by .catch() so i think you must be running a bad/old nodejs version, or the code you provided is not complete, and the failure is elsewere. I dont see any line pointing to your own code in the log O_o (only node_modules).
which nodejs version is it ?
var p = new Promise((resolve, reject) => {
throw new Error('test');
resolve('ok')
})
p.then(console.log).catch(function(err) {
console.error('err', err)
});

Dropbox's `filesGetTemporaryLink` throws an uncatchable `UnhandledPromiseRejectionWarning` and terminates Node.js

To get a download link to the file hosted on Dropbox, I'm using a Dropbox JavaScript API (7.0.0):
export const fileDownload = async function fileDownload(fileUUID) {
let isSucceeded;
let message;
let file;
const dbx = _dropboxFactory();
try {
const operationResult = await dbx.filesGetTemporaryLink({
path: `/${CONFIG_STORAGE.uploader.assetsPath}/${fileUUID}`
});
if ("OK" === http.STATUS_CODES[operationResult.status].toUpperCase()) {
file = Object.freeze({
length: operationResult?.result?.metadata?.size,
link: operationResult?.result?.link,
mime: mime.lookup(operationResult?.result?.metadata?.name),
name: operationResult?.result?.metadata?.name
});
isSucceeded = true;
message = SYS_MESSAGES.storageFileDownloadSucceeded.code;
} else {
isSucceeded = false;
message = SYS_MESSAGES.storageFileDownloadFailed.code;
}
} catch (err) {
file = "error";
isSucceeded = false;
message = "FIL_NOT_FOUND";
}
const downloadResult = Object.freeze({
file,
isSucceeded,
message
});
return downloadResult;
};
The problem is that when the path to the file is wrong, I get a Node.js exception:
(node:9156) UnhandledPromiseRejectionWarning: #<Object>
(node:9156) 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:9156) [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've tested several options and came to conclusion that the issue is in:
const operationResult = await dbx.filesGetTemporaryLink({
path: `/${CONFIG_STORAGE.uploader.assetsPath}/${fileUUID}`
});
My questions:
Why does Node.js claim «unhandled promise rejection» or «promise which was not handled with .catch()» and throws an UnhandledPromiseRejectionWarning exception if the code, which generates it is wrapped by try-catch?
Starting Node.js 15.x.x, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code. Therefore, how to avoid UnhandledPromiseRejectionWarning?
A temporal workaround:
To run Node.js with a flag --unhandled-rejections=warn.
This will prevent the termination of the Node.js process with a non-zero exit code upon UnhandledPromiseRejectionWarning.
The problem was in the Dropbox library and has been solved by the Dropbox team with the release of 7.1.0. After upgrading the code in the question works correctly.
try changing your fileResponse function to something like this. You are mixing up async/await with .then().catch() style syntax.
Just wrap your function in a try-catch
async function getDocument() {
try {
const response = await fetch(`${http() + ip}/downloadDocument`, {
body: JSON.stringify({fileUUID: oModel.oData[0].documentFile}),
cache: "no-cache",
credentials: "same-origin",
headers: {
"Content-Type": "application/json"
},
method: "POST",
mode: "cors"
});
const data = await response.json();
return data;
} catch(err) {
console.log(err);
}
}

How to pass read data from await readFile to writeFile in fs module of node.js?

In this code, file is being opened and read successfully.
var objFs = require('fs')
async function openFile() {
await objFs.open('new.js', 'r', (argError, argFD) => {
if (argError)
throw -1
else
console.log("File opened!")
})
// This object is the promise.
const objReadResult = await objFs.readFile('new.js', (argError, argData) => {
if (argError)
throw 2
else
console.log('File read!')
})
await objFs.writeFile('new.js', (argError, objReadResult) => {
try
{
if( argError )
throw argError
else
console.log("File written")
}
catch( arg )
{
console.log(arg)
}
})
}
openFile()
What is the way to extract the data from await of readFile and pass it to writeFile?
The way I have written the writeFile function is producing the following error:
(node:21737) UnhandledPromiseRejectionWarning: TypeError [ERR_INVALID_CALLBACK]: Callback must be a function. Received undefined
at maybeCallback (fs.js:145:9)
at Object.writeFile (fs.js:1332:14)
at openFile (/home/sulakshana/Documents/nodejs/programs/async_await.js:29:14)
(node:21737) 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:21737) [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.
File opened!
File read!
Few issues I can see:
there is a mix of syntaxes - async/await while also providing callbacks to the fs calls;
no need to call fs.open before fs.readFile;
there are no data to be written in fs.writeFile [docs];
there should be await-ing at the end;
and the final (the actual error reported) - there should be try...catch block to catch and react to any errors that occur.
Example implementation:
const fs = require('fs').promises;
async function openFile() {
const objReadResult = await fs.readFile('new.js');
console.log('File read!');
await fs.writeFile('new.js', /* PROVIDE DATA TO WRITE */);
console.log('File written');
}
(async () => {
try {
await openFile();
console.log('Program is done');
} catch (err) {
console.error(err);
}
})();

How to solve UnhandledPromiseRejectionWarning in NodeJS testing framework

I'm using custom commands in my testing framework based on Nightwatch.js. I want to do a PUT request via superagent. This os my custom command:
const superagent = require("superagent");
exports.command = function(url, header, body, callback) {
return superagent
.put(url)
.send(body) // sends a JSON post body
.set(header)
.then(result => {
callback(true, result);
return this;
})
.catch(err => {
if (err) {
callback(false, err);
return this;
}
});
};
And this command I'm using in my tests:
return client
.apiPut(apiUrl, header, body, function(status, result) {
assert.isTrue(status, "response status is false");
assert.isTrue(result.ok, "response result is NOT ok");
})
If everything is fine with the PUT request (status == true and successful response) then everything is fine and the test will finish, but if the PUT request is not successful (status != true and an error as result) I'm getting the following error message and the current Node process does not finish:
09:11:12 (node:103) UnhandledPromiseRejectionWarning: AssertionError: response status is false: expected false to be true
09:11:12 at /var/jenkins_home/jobs/MYJOB/workspace/testautomation/end2end-web-tests/pageobjects/MyPageView.js:59:20
09:11:12 at superagent.put.send.set.then.catch.err (/var/jenkins_home/jobs/MYJOB/workspace/testautomation/end2end-web-tests/commands/apiPut.js:14:9)
09:11:12 at <anonymous>
09:11:12 at process._tickCallback (internal/process/next_tick.js:189:7)
09:11:12 (node:103) 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)
09:11:12 (node:103) [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.
But I don't know what I'm doing wrong with the callback in my custom command. What should I do to solve that issue?
Thanks for the help. Now it is running. I've replaced the promise and replaced it completely with callbacks. Now it is working :)
const superagent = require("superagent");
exports.command = function(url, header, body, callback) {
return superagent
.put(url)
.send(body) // sends a JSON post body
.set(header)
.end((error, result) => {
if (error) {
callback(false, result, error);
} else {
callback(true, result, error);
}
});
};

Categories

Resources