Using Node.js with JavaScript to retrieve an element by its ID with the document

There is a Node.js script (app.js) that sends an email:

const { response } = require("express");
const express = require("express");
const nodemailer = require("nodemailer");
const app = express();
const port = 5000;

//
function sendEmail(tel) {
  return new Promise((resolve, reject) => {
    var transporter = nodemailer.createTransport({
      service: "gmail",
      auth: {
        user: ,
        pass: ,
      },
    });
    const mail_configs = {
      from: "myEmail",
      to: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="43223137262e273527032e222a2e5c3136">[email protected]</a>",
      subject: "Testing Koding 101 Email",
      text: "tel",
    };
    transporter.sendMail(mail_configs, function (error, info) {
      if (error) {
        console.log(error);
        return reject({ message: "An error has occurred" });
      }
      return resolve({ message: "Email sent successfully" });
    });
  });
}

app.get("/", (req, res) => {
  sendEmail()
    .then((response) => res.send(response.message))
    .catch((error) => res.status(500).send(error.message));
});

app.listen(port, () => {
  console.log(`nodemailerProject is listening at http://localhost:${port}`);
});


There is a button in another JS file which runs this JS script and sends an email when the button is clicked:

let input = document.getElementById("phonenumber");

head.addEventListener("click", function () {
  fetch("http://localhost:5000/")
    .then((response) => response.json())
    .then((data) => console.log(data))
    .catch((error) => console.error(error));
});

There is an input field for typing a message in the HTML file

<input id="phonenumber" class="text-order" type="text"
        placeholder="___________"'/>

How can we send the value entered in this input as an email message when a button is pressed?

Answer №1

The Fetch API allows for a second parameter, which is an options object. This is where you can pass your input data. To capture the value of an input element, such as:

let input = document.getElementById("phonenumber");

You can access the value using input.value. By including this value in the body property of your options object, it will be sent in the request body to the server.

For example:

fetch("http://localhost:5000/", {
  body: JSON.stringify(input.value)
})

If you are also listening for a click on another element (head), you may need to use an onChange handler on the input to store the value locally. Then, when the other element is clicked, you can pass the value into the fetch options.

Below is an example syntax for sending options using the Fetch API, showcasing various options it supports:

// Example POST method implementation:
async function postData(url = '', data = {}) {
  // Default options are marked with *
  const response = await fetch(url, {
    method: 'POST', // *GET, POST, PUT, DELETE, etc.
    mode: 'cors', // no-cors, *cors, same-origin
    cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
    credentials: 'same-origin', // include, *same-origin, omit
    headers: {
      'Content-Type': 'application/json'
      // 'Content-Type': 'application/x-www-form-urlencoded',
    },
    redirect: 'follow', // manual, *follow, error
    referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
    body: JSON.stringify(data) // body data type must match "Content-Type" header
  });
  return response.json(); // parses JSON response into native JavaScript objects
}

postData('https://example.com/answer', { answer: 42 })
  .then((data) => {
    console.log(data); // JSON data parsed by `data.json()` call
  });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

A link is not allowed to be a child of another link

An issue arises in a React.js application Warning: validateDOMNesting(...): <a> cannot be nested under another <a>. Refer to Element > a > ... > a for more information. What is the significance of this warning? How can it be avoided ...

What is the best way to keep my bottom navigation bar attached to my top navigation bar?

I am facing an issue with my two navbars. The top navbar sticks to the top of the page when the user scrolls down, which works perfectly fine. However, when the user logs in, the bottom navbar becomes visible. Unfortunately, the bottom navbar is not sticky ...

Updating a Vue ref does not result in the component reflecting the changes made

My Vue3 form has three text inputs and a group of checkboxes. To implement this, I am using the bootstrap-vue form along with its checkbox-group component. After calling an API to fetch default values for the form, I update the ref as shown below. Interes ...

deploying node application on AWS

I'm currently facing an issue with my node app on AWS. The actual page is not loading and I suspect there might be an error in my server.js file. When I try running a boilerplate node app on my AWS instance and SSH into it, everything works fine. Howe ...

Show information in a horizontal layout, but switch to a stacked arrangement if the screen is too narrow

Is there an optimal way to arrange content side by side when the width allows, like this: [content] [content] [content] [content] If the screen becomes too small, should the content automatically stack like this: [content] [content] [content] I am ...

Error: The injected script in Angular 2 using JSONP did not trigger the specified callback function

I am currently utilizing Angular 2.RC4 along with typescript Within my class, I have the following data: import {Injectable, Injector, ReflectiveInjector} from '@angular/core'; import { Http, Response, Headers, RequestOptions, HTTP_PROV ...

Incorporating stick-to-top scroll functionality using AngularJS and ng

I am trying to implement a 'sticky' scroll on dynamic content. My current working example can be found here. It seems to be working, but I encounter a small 'flicker' when new items are appended. This issue seems to be related to the se ...

Jquery Error: An issue occurred with $.getJSON

While working with a JSON file and using $.getJSON method... $.getJSON('data.json', function(obj){ $.each(obj, function(key, value){ $.each(value, function(keys, values){ console.log(values.title); }); }); }); An err ...

Is it acceptable to store HTML in a content database?

I am considering storing HTML in a database, but I want to ensure it is safe. If I restrict who can submit the content, do you think it would be secure enough? My question is quite straightforward. I run a platform that provides video tutorials and variou ...

Is JSDOM capable of configuring exuberant ctags for a project setup?

Anticipating great javascript ctags support got me considering the possibility of using a project like to configure ctags for optimum vim usage. ...

How can I stick the footer to the bottom of the page?

I've tried numerous codes in an attempt to make the footer stay at the bottom of the page, however, none of them seemed to work. Here's my footer tag: <footer class="container py-5 navbar-fixed-bottom"> The following div is: <di ...

When trying to call a function from a different component, the object inside the function is not being

Sorry for not giving a proper title to my question. Let me explain the problem I am facing. I have two Components - A and B. In Component B, there is a function called saveIndCustData which emits and saves data. export class CustomerformComponent implemen ...

Perform fn(param1, param2) within a callback using AngularJS ng-click syntax

When using AngularJS (and likely in other frameworks as well), you have the ability to pass a function with parameters to ng-click like this: <div ng-click="myFunc(param)">Click Me</div> I am interested in achieving the same functionality by ...

Utilizing Bootstrap and flexbox to create a card: repositioning the image to the left or right

Currently, I am attempting to construct a card layout using Bootstrap 4 with flexbox enabled. The image below depicts my current implementation, which is functioning as expected. https://i.sstatic.net/huXvo.jpg Here is the HTML structure: <section> ...

Refresh the DOM following a jQuery load operation

Recently, I integrated the Jquery Load($('body').load('/some.html')) function into my application. There are plenty of other jquery codes in my application initialized as $('#id'). Instead of transforming all these codes into ...

What could be the reason for jquery not functioning properly on my website?

Hey there! I'm running into an issue where my jQuery code isn't running. I've tried triggering it on button click or page load, but no luck so far. Any tips would be greatly appreciated. Thanks! <head> <script src ...

The array becomes empty after a value has been assigned to it

I am currently working with a variable containing JSON data. var blogData = [ { "blogTitle":"Bangladesh", "imagePath":"/img/blog/bangladesh.jpg" },{ "blogTitle":"In ...

Enhance Bootstrap: adjust button width based on fluid text width

Incorporating Bootstrap 5 framework, I have designed a card that showcases brand information along with a navigation button on the right side. https://i.sstatic.net/25QVr.png When the description is brief, the button aligns perfectly in a single line. Ho ...

I am struggling to grasp the flow of this code execution

Hi there, I just started my journey in JavaScript learning about two weeks ago. I would really appreciate it if someone could walk me through the execution steps of the code provided below. function sort(nums) { function minIndex(left, right) { ...

Encountering an Ajax Issue with Laravel 5.4

I encountered the following error: "{"status":"error","msg":"Category was not created"}" Below is my Controller Function where I execute the action : function create_category(Request $request){ if($request->ajax()){ $c ...