This question already has answers here:
Javascript require() function giving ReferenceError: require is not defined
(6 answers)
Closed 2 years ago.
when I tried to send an email using nodemailer, after I insert these into my web project, and I get an error "require is not defined". Can I know how to solve it?
var nodemailer = require('nodemailer');
var transporter = nodemailer.createTransport({
service:'gmail',
auth:{
user:'xxx#gmail.com',
pass:'xxxxxxx'
}
});
var mailOptions = {
from:'xxx#gmail.com',
to: 'xxx#gmail.com',
subject:'Thanks for using!',
text:'Thanks!'
};
transporter.sendMail(mailOptions,function(error, info){
if(error){
console.log(error);
}else
console.log('Email sent: '+ info.response);
});
I am assuming you are trying to do this on the frontend. Nodemailer is a package that is made to be run on a backend node.js server. You do not have node listed for the questions tags so that is why I am assuming this. If this is not the case then check out:
http://requirejs.org/docs/download.html
Add this to your project: https://requirejs.org/docs/release/2.3.5/minified/require.js
and take a look at this http://requirejs.org/docs/api.html
Related
This question already has answers here:
ReferenceError: Headers is not defined in Google scripts
(1 answer)
How to get an audio response from an API call within google app to play in speakers
(1 answer)
FileReader not defined in Apps Script
(1 answer)
How to use payload with method get?
(1 answer)
Which JavaScript features are available in Google Apps scripts?
(1 answer)
Closed 4 months ago.
This post was edited and submitted for review 4 months ago and failed to reopen the post:
Original close reason(s) were not resolved
I am trying to access an API in an apps scripts function. I have tested my code in VS code and it works just fine, but when I run it in apps scripts, I get an error saying "ReferenceError: URLSearchParams is not defined". Does anyone know of a fix? None of the similar questions offer a viable solution.
Code:
async function ApiTest() {
let status = "watching";
let num_watched_episodes = 10;
let token = "MyTokenIsHere";
let id = 50346;
const urlParams = new URLSearchParams({
status: status,
num_watched_episodes: num_watched_episodes,
});
fetch('https://api.myanimelist.net/v2/anime/' + id + '/my_list_status', {
method: "PATCH",
headers: {
'Authorization': 'Bearer ' + token,
},
body: urlParams,
})
}
I am attempting to send an email using Nodemailer and Twilio Sendgrid, following the tutorial here. As far as I can tell I am following the instructions in the tutorial, as well as theNodemailer and Sendgrid documentation. Every time this method is called, the code in the catch block executes, and I get the error Error: Missing credentials for "PLAIN".
My question was closed due to association with the question here, however my problem is different and none of the solutions on the thread apply. I am using my own domain to send, not gmail.com. I want to solve the problem without using Oauth2, which from what I understand I should not need, given that I am using an email domain I control. Also I am already using pass' rather than 'password for my authorization data (the top solution on the associated answer).
I've been stuck on this for a few days now , and I'd appreciate any insight anyone can offer!
Here is my code:
async function sendEmail(email, code) {
try{
const smtpEndpoint = "smtp.sendgrid.net";
const port = 465;
const senderAddress = 'Name "contact#mydomain.com"';
const toAddress = email;
const smtpUsername = "apikey";
const smtpPassword = process.env.SG_APIKEY;
const subject = "Verify your email";
var body_html = `<!DOCTYPE>
<html>
<body>
<p>Your authentication code is : </p> <b>${code}</b>
</body>
</html>`;
let transporter = nodemailer.createTransport({
host: smtpEndpoint,
port: port,
secure: true,
auth: {
user: smtpUsername,
pass: smtpPassword,
},
logger: true,
debug: true,
});
let mailOptions = {
from: senderAddress,
to: toAddress,
subject: subject,
html: body_html,
};
let info = await transporter.sendMail(mailOptions);
return { error: false };
} catch (error) {
console.error("send-email-error", error);
return {
error: true,
message: "Cannot send email",
};
}
}
And here is the log:
Thanks!
You have already identified the issue of API key not being passed into the Nodemailer transport. While hardcoding the key is a possible solution, it's not a good practice. Usually secrets and keys are managed via environment variables so they are, for example, not accidentally committed to a repository and can be configured externally without changing the code.
In the tutorial you linked, working with the environment variable is addressed, but I see there is a mistake with .env file. So let me try to recap how to properly get SG_APIKEY from environment variable and .env file.
In your project directory create the .env file with the following contents:
SG_APIKEY=<your_sendgrid_api_key>
(obviously replace <your_sendgrid_api_key> with your actual API key)
Make sure dotenv package is installed: npm i dotenv
At the beginning of the file where you use Nodemailer, add the following line:
require("dotenv").config();
This will ensure the SG_APIKEY is loaded from .env file.
You can check if the env variable is set correctly with console.log(process.env.SG_APIKEY)
A comment on the (closed) previous version of this thread solved the problem for me:
This question already has an answer here:
Firebase Cloud Functions throws a DNS error when calling an external API [duplicate]
(1 answer)
Closed 4 years ago.
I have been assigned on a task to fetch all tweets from a certain hashtag and send that data to my application. So I decided to use firebase cloud functions, I generated the key needed for the twitter api. I also tested get my homepage using postman status and worked, however my issue now when I test my code on good cloud functions I cant get it to work and the error message when I try this end point:
Error: could not handle the request
https://us-central1-don.cloudfunctions.net/api/
or
https://us-central1-don.cloudfunctions.net/api/statuses/user_timeline
and this is my code on firebase cloud functions
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const express = require('express');
const Twitter = require('twitter');
admin.initializeApp(functions.config().firebase);
const client = new Twitter({
consumer_key: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
consumer_secret: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
access_token_key: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
access_token_secret: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
});
const app = express();
/* Express */
app.get('/', function(req,res){
client.get('statuses/user_timeline', {screen_name: 'nodejs', count: 5}, function (error, tweets, response) {
if (!error) {
response.send({ title: 'Express', tweets: tweets })
}
else {
response.send({ error: "this is error: " + error })
}
});
});
// Cloud Function
exports.api = functions.https.onRequest(app)
Hope anyone can suggest any solutions, thanks.
Update: here is my function console where it also throws an error:
api Function execution took 8 ms, finished with status code: 404
api Billing account not configured. External network is not accessible
and quotas are severely limited. Configure billing account to remove
these restrictions
As mentioned in the comments, you should upgrade to a paid plan, you may find this other Stack Overflow question useful : Cloud Functions for Firebase - Billing account not configured
Hope this helps!
This question already has answers here:
How to list all MongoDB databases in Node.js?
(5 answers)
Closed 6 years ago.
I have seen answers on C# and Java but not able to find anything on NodeJs. I have tried using cmd shell in Windows to get the required output but no luck.
I am aware that the same information can be taken in Mongo shell but the requirement is to get a list within the NodeJs app.
cmd = child_process.exec('"C:\\Program Files\\MongoDB\\Server\\3.2\\bin\\mongo.exe" admin ; db.getMongo().getDBNames()');
and also
var mongoServer = require('mongodb-core').Server;
var server = new mongoServer({
host: 'localhost'
, port: 27017
, reconnect: true
, reconnectInterval: 50 });
server.on('connect', function (_server) {
console.log('connected');
var cmdres = _server.command('db.adminCommand({listDatabases: 1})');
console.log("Result: " + cmdres);
}
You can use mongodb driver to get dbs as following
var MongoClient = require('mongodb').MongoClient;
// Connection url
var url = 'mongodb://localhost:27017/test';
// Connect using MongoClient
MongoClient.connect(url, function(err, db) {
// Use the admin database for the operation
var adminDb = db.admin();
// List all the available databases
adminDb.listDatabases(function(err, result) {
console.log(result.databases);
db.close();
});
});
Reference: http://mongodb.github.io/node-mongodb-native/2.2/api/
See this answer
db.admin().listDatabases
This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 7 years ago.
So, I'm trying to send an email confirmation token to an user, and for that, I'm trying to use the crypto module to generate the token. I have this:
var transport = this.NewTransport(), // This generates a nodemailer transport
token;
// Generates the token
require('crypto').randomBytes(48, function(ex, buf) {
token = buf.toString('hex');
});
// Uses nodemailer to send the message, with the token.
var message = {
from: 'test#email.com',
to: 'receiver#email.com',
subject: 'Token',
text: token,
html: token
};
transport.sendMail(message, function(err){
if(err) return res.send({s: 0});
return res.send({s: 1});
});
Well, the token generated by the crypto module isn't getting assigned to the token variable, I assume this is because of the asynchronous nature of the randomBytes function.
How can I actually... save the token somewhere so I can send it through the email? Or do I have to include ALL of the email-sending code inside of the randomBytes callback function? Is this the way it has to be done in node? Is there any other way, so that the token gets generated in time, and actually sent?
Sorry, I'm quite new to node and I'm still confused about callbacks sometimes. Thanks.
You should really wrap your code within functions. It makes it easier to manage callbacks and simultaneously maintain the code. Have a look at how I reworked what you provided... Keep in mind I haven't checked the code so there may be a few bugs.
var crypto = require('crypto'),
transport = this.NewTransport(); // This generates a nodemailer transport
generateToken(sendMail);
function generateToken(callback) {
// Generates the token
var token;
crypto.randomBytes(48, function(ex, buf) {
token = buf.toString('hex');
if (typeof callback === 'function') {
callback(token);
}
});
}
function sendMail(token) {
// Uses nodemailer to send the message, with the token.
var message = {
from: 'test#email.com',
to: 'receiver#email.com',
subject: 'Token',
text: token,
html: token
};
transport.sendMail(message, function(err){
if(err) return res.send({s: 0});
return res.send({s: 1});
});
}