What is the best way to save the text entered into an HTML input field into a variable in node.js?

Here is a sample of my node.js code:

const connect = require('connect'); 
const serveStatic = require('serve-static'); 

connect().use(serveStatic("WebDir")).listen(80, function(){ 
    console.log('Server running on port 80...'); 
});

I am looking to integrate an API and retrieve data from an HTML input field in node.js. The input field is a standard HTML input element.

Answer №1

Using Node.js Express, you can easily set up a test environment for this.

You will need 2 files: index.js and index.html

index.html

<html>
<head>
      <script src="https://code.jquery.com/jquery-3.3.1.js"></script>
      <script type="text/javascript">

        var sendInput = function() {
            var inputField = $('#inputField').val();

            console.log(inputField);

            $.ajax({
                type: 'POST',
                url:  'http://localhost:3000/inputData',
                crossDomain: true,
                data: JSON.stringify({ inputField: inputField }),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(result, status){
                    document.getElementById("output").innerHTML = result.nodeVariable;
                },
                error: function (errorMessage) {
                    console.error('Error: ', errorMessage);
                }
            });
        }

      </script>
</head>
<body topmargin="40" leftmargin="40">
 <div id="result">Loading..</div>
 </br>
 <button onClick="sendInput()">Send input to Node.js</button> : <input type="text" id="inputField" value="test value"><br>
 <div>
 <br/>Result: <p id="output"></p>
 <div>
 </body>
</html>

This is the server-side node.js script:

index.js

const bodyParser = require('body-parser');
const express = require('express');
const port = (process.env.PORT || 3000);

const app = express();

app.use(express.static(__dirname));
app.use(bodyParser.json());

app.post('/inputData', (req, res, next) => {

    console.log('/inputData post: ', JSON.stringify(req.body));
    // Read the variable..
    var inputField = req.body.inputField;
    console.log('Input field: ', inputField);

    res.status(201).send(JSON.stringify({status: 'OK',  nodeVariable: inputField + " - updated by node."}))
});

app.listen(port);
console.log('Express listening on port ' + port);

To test, visit http://localhost:3000 in your browser.

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

Identifying an anonymous function with a name (using .name versus .displayName)

In the context of my react native project, I have come across a function with an undefined name that is not being inferred. This function looks like: const f = function() {}; Despite maintaining its anonymous definition, there is an attempt to assign a na ...

Generating a safe POST connection with express.js

Is there a simple method to generate a link for submitting a POST request using Express.js or a plugin? This approach can also be employed to enhance security for important actions like user deletion, including CSRF protection. In some PHP frameworks lik ...

Rotating a path in Three.js: A beginner's guide

I am a beginner with three.js and I am trying to make an object move along an ellipse curve. However, when I rotate the ellipse using ellipse.rotation.y, the object no longer follows the path correctly. It continues to move along the original path instead. ...

Refreshing the browser causes the URL to be updated due to the utilization of $routeProvider for client-side routing

Currently, I am developing a single-page application using Angular for the client-side and Nodejs (Express) for the server-side. To manage different views and browser history, I am utilizing $routeProvider in Angular. While everything works smoothly withou ...

Creating a Circular Cropping Tool with jQuery

Can anyone help with a jQuery/javascript script that can be used to select a circle on an image and then provide the coordinates to a PHP/GD script for cropping or blurring that image? Appreciate any assistance. Thank you. ...

Issue with Bootstrap card collapsing and merging with other cards

I am using Bootstrap to design a grid of cards, but I am facing an issue where all the cards are merging together when I resize the screen. This issue occurred when I attempted to position the icons to appear at the top left of the card and the bottom midd ...

The Go to Top button functions exclusively on the Homepage

Check out my website: viettech-ca. com Take a look at my code: <div class="wrap footer-nav mgt35"> <ul> <li><a href="bvct/chi-tiet/12/gioi-thieu.html">About Us</a></li> <li><a href="/bvct/chi-tiet/13/dai-ly.ht ...

Reactjs may have an undefined value for Object

I have already searched for the solution to this question on stackoverflow, but I am still confused. I tried using the same answer they provided but I am still getting an error. Can someone please help me resolve this issue? Thank you. const typeValue = [ ...

a novel approach within angular2

Just starting out with Angular 2. Could someone shed some light on the difference between html directives and attribute directives? And why are they both necessary? For instance: <rating [rate]="rate" (rate-change)="onUpdate($event)"></rating&g ...

Adding color to the header's top section and leaving the navigation bar untouched

A few days ago, I posted a question on this platform regarding customizing CSS related to search forms within Bootstrap. The response I received from Charlie was incredibly helpful in refining the code for my header and navigation elements. You can view hi ...

Aligning Material-UI Text Field with a Paragraph

I'm currently working on a React app that has a "mad-libs" style and I'm facing some challenges trying to align a couple of components. The image below shows the current situation along with an arrow pointing to the desired outcome. It seems like ...

Looking to transform an HTML table into a stylish CSS layout complete with a form submission button?

Recently, I've been delving into the world of CSS and PHP as I work on converting old code entirely into HTML and PHP with a touch of CSS. The visual aspect seems fine, but I've hit a roadblock with the submit form due to an IF statement in PHP. ...

When the onClick event is triggered, my intention is to dynamically insert a new

I'm having trouble adding a new row on each click, as my code keeps replacing the existing row. I attempted moving the if statement outside the addTable function, but it didn't work as expected. I've tried multiple solutions without succes ...

Guide on utilizing Thymeleaf for dynamic updates in a table

My code includes a segment like this: <div class="ui-table"> <div class="items"> <div class="justify-content-end d-flex"> <span class="text- ...

Backgrounds filled by nested <li> elements inside another <li> element

My website features a sidebar menu with nested lists. When hovering over a list item, a sub-list appears. However, I am having an issue where the background color fills the entire sub-list instead of just the first list item. See the images below for clari ...

Changing the title of a jQuery DataTable with a button click

Within my view, there are two input fields, a button, and a table that is utilizing jQuery DataTables. The datatable has a print functionality integrated into it. I am attempting to customize the title of the print page based on the values inputted into ...

Using useEffect for React login validation

I'm currently working on implementing a login feature in my React application using hooks. My approach involves using the useEffect hook to make an API call for credentials, and then updating the state in context. However, I've encountered an iss ...

Submitting an extremely large string to an Express server using JS

How can a large String be efficiently sent to a Node.js Express server? On my webpage, I am using Codemirror to load files from an Express server into the editor. However, what is the most effective method for sending "the file" (which is actually a bi ...

Alexa Account Linking - Error: Account linking credentials are not valid

I've been working on setting up an Alexa skill with account linking. After obtaining the Linking Authorization Code and exchanging it for an Access Token, I attempted to input all the necessary parameters: code, access token, and skill ID into the Ale ...

The input must be a 24-character string consisting of hex characters - that's what I believe

I have developed a method that allows me to locate a specific document in my database using its ObjectID: console.log('id: ' + id + ' type: ' + typeof id); collection.findOne({'_id':new ObjectID(id)}, function(err ...