Categories
JavaScript Answers

How to fix username and password not accepted when using Nodemailer?

To fix username and password not accepted when using Nodemailer, we set the auth property when we create the transporter object.

For instance, we write

const nodemailer = require("nodemailer");

const transporter = nodemailer.createTransport({
  service: "gmail",
  auth: {
    user: "YOUR-USERNAME",
    pass: "THE-GENERATED-APP-PASSWORD",
  },
});

const send = async () => {
  const result = await transporter.sendMail({
    from: "YOUR-USERNAME",
    to: "RECEIVERS",
    subject: "Hello World",
    text: "Hello World",
  });

  console.log(JSON.stringify(result, null, 4));
};
send();

to call createTransport with an object with the auth property set to an object with the username and password.

Then we call sendMail to send the message with the from, to, subject and text fields for the email.

It returns a promise with the result of the transmission.

Categories
JavaScript Answers

How to fix Missing credentials in config, if using AWS_CONFIG_FILE, set AWS_SDK_LOAD_CONFIG=1 with Node?

To fix Missing credentials in config, if using AWS_CONFIG_FILE, set AWS_SDK_LOAD_CONFIG=1 with Node, we need to add the credentials into our environment variables.

To do this, we run

$ export AWS_ACCESS_KEY_ID="your_key_id"
$ export AWS_SECRET_ACCESS_KEY="your_secret_key"

in Unix to set the AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables.

We do the same thing with

> set AWS_ACCESS_KEY_ID="your_key_id"
> set AWS_SECRET_ACCESS_KEY="your_secret_key"

on Windows.

We can also create a ~/.aws/credentials file with

[default]
aws_access_key_id = <YOUR_ACCESS_KEY_ID>
aws_secret_access_key = <YOUR_SECRET_ACCESS_KEY>
Categories
JavaScript Answers

How to get path from the request with Node.js?

To get path from the request with Node.js, we get the URL from the req object.

For instance, we write

const api = express.Router();

api.use((req, res, next) => {
  const fullUrl = req.protocol + "://" + req.get("host") + req.originalUrl;
  next();
});

app.use("/", api);

to get the request URL’s protocol with req.protocol

We get the request URL’s host name with req.get("host").

And we get the rest of the request URL with req.originalUrl.

Categories
JavaScript Answers

How to use sprintf with Node.js?

To use sprintf with Node.js, we use the util.format method.

For instance, we write

const s = util.format("hello %s", "world");

to call util.format to return a formatted string with %s filled in with the arguments after the first.

Therefore, s is 'hello world'.

Categories
JavaScript Answers

How to get the string length in bytes in Node?

To get the string length in bytes in Node, we call the Buffer.byteLength method.

For instance, we write

const getBytes = (string) => {
  return Buffer.byteLength(string, "utf8");
};

to call Buffer.byteLength with the string to get the string‘s length in byte.