Categories
JavaScript Answers

How to POST data with request module on Node.js?

To POST data with request module on Node.js, we call the request.post method.

For instance, we write

const request = require("request");

request.post(
  {
    headers: { "content-type": "application/x-www-form-urlencoded" },
    url: "http://localhost/test2.php",
    body: "mes=heydude",
  },
  (error, response, body) => {
    console.log(body);
  }
);

to call request.post with an object that has the headers, url and the request body.

We get the response and the response body from the callback.

Categories
JavaScript Answers

How to fix the upstream dependency conflict installing NPM packages with JavaScript?

To fix the upstream dependency conflict installing NPM packages with JavaScript, we run npm install with the --legacy-peer-deps option.

For instance, we run

npm install --legacy-peer-deps

to install all packages in package.json with the packages’ peer depdendencies.

Categories
JavaScript Answers

How to use Nodemailer with Gmail and Node.js and JavaScript?

To use Nodemailer with Gmail and Node.js and JavaScript, we call the sendMail method.

For instance, we write

const nodemailer = require("nodemailer");
const smtpTransport = require("nodemailer-smtp-transport");

const transporter = nodemailer.createTransport(
  smtpTransport({
    service: "gmail",
    host: "smtp.gmail.com",
    auth: {
      user: "somerealemail@gmail.com",
      pass: "realpasswordforaboveaccount",
    },
  })
);

const mailOptions = {
  from: "somerealemail@gmail.com",
  to: "friend@gmail.com",
  subject: "Sending Email using Node.js[nodemailer]",
  text: "That was easy!",
};

transporter.sendMail(mailOptions, (error, info) => {
  if (error) {
    console.log(error);
  } else {
    console.log("Email sent: " + info.response);
  }
});

to create a transporter object with the createTransport method.

We call it with the object returned by smtpTransport with the username, password, and server host name to send email via SMTP.

Then we create the mailOptions object with the email options.

We call transporter.sendMail method with the mailOptions to send the message.

Categories
JavaScript Answers

How to generate random SHA1 hash to use as ID in Node.js?

To generate random SHA1 hash to use as ID in Node.js, we use the crypto.randomBytes method.

For instance, we write

const id = crypto.randomBytes(20).toString("hex");

to call randomBytes to create a byte object with 20 bytes.

Then we call toString on it with 'hex' to convert it to a hex string.

Categories
JavaScript Answers

How to set HTML5 required attribute in JavaScript?

To set HTML5 required attribute in JavaScript, we set the required property.

For instance, we write

document.getElementById("edName").required = true;

to select the input with getElementById.

And then we set its required property to true to make it a required input.