Three examples of nodejs methods to obtain form data

Three examples of nodejs methods to obtain form data

Preface

Nodejs is a server-side language. During development, registration and login, etc. need to send data to the backend through a form for judgment. So, as a server-side language, what methods can nodejs use to receive the post request value of the call form?

The following three are commonly used. Let's look at their specific usage with examples.

We use the express plug-in in the backend, so you need to know something about express to read it easily~

1. First, initialize npm, download the express package, import the module and create a service object

//Import the express module const express = require("express");
// Create a server object const app = express();

form form delivery

This feature of the from form allows you to click a button in the form whose type is submit, which will submit the form data. The form is in an object format. The attribute name is the name value in the input tag, and the attribute value is the value of the input tag. The following example shows the specific writing method.

<form action="/todata" method="POST">
        <table>
            <tr>
                <td>Name</td>
                <td> <input type="text" name="user" id=""></td>
            </tr>
            <tr>
                <td>Password</td>
                <td> <input type="text" name="password" id=""></td>
            </tr>
            <tr>
                <button type="submit">Submit</button>
            </tr>
        </table>
</form>

Since form submission is a post request, the backend nodejs code needs to parse the response header of the post request data and then use app.use(bodyParser.urlencoded({ extended: false })) to represent the data passed from the front end. The specific backend code is as follows.

const express = require("express");
const app = express();
app.use(express.static("./"))
var bodyParser = require('body-parser')
// Parse application/x-www-form-urlencoded response header app.use(bodyParser.urlencoded({ extended: false }))
app.post("/todata",(req,res)=>{
    console.log(req.body);
    res.send("Submission successful")
})
app.listen("80",()=>{
    console.log("success");
})

Run the node code through the terminal to see the results

ajax request passing

When sending requests to the backend, get and post requests are often used. Similarly, form data can be sent to the backend via ajax post requests. Based on the above example, the front-end code of this method is as follows.

	 $("#inp3").on("click",function(){
        let user = $("#inp1").val();
        let password = $("#inp2").val();
        $.ajax({
        url:"todata",
        type:"post",
        data:{
            user,
            password
        },
        success:(data)=>{
            alert(data)
        }
         })
    })

Here, we get the values ​​of the two inputs, and then bind the submit button to send an ajax request. The data sent to the backend is stored in the data attribute. The backend also obtains it through req.body. It is important to note that the form does not need to write an action value, and the button in the form needs to prevent the default behavior (otherwise the request will be sent directly when clicked, causing the ajax request to fail), or use the input tag type as button type.

Form Serialization

This method of sending is a common method of form submission. It also sends the request through ajax, and the name attribute can also be sent directly as the attribute name of the backend. It can be said to be a combination of the above two methods.

		$("#inp3").on("click",function(){
        $.ajax({
        url:"todata",
        type:"post",
        data:$("form").serialize(),
        success:(data)=>{
            alert(data)
        }
         })
    })

You only need to use the $("form").serialize() method to get the value of the name attribute.

Summarize

This is the end of this article about how to get form data with nodejs. For more information about how to get form data with nodejs, please search previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • How to get form data in Vue
  • How to get data list display in Vue
  • Vue get form value example
  • Nodejs obtains network data and generates Excel tables
  • Detailed explanation of how to obtain multiple table data using vue+nodejs

<<:  Mysql dynamically updates the database script example explanation

>>:  Detailed tutorial on how to automatically install CentOS7.6 using PXE

Recommend

Explanation of the problem of selecting MySQL storage time type

The datetime type is usually used to store time i...

Detailed explanation of the functions of each port of Tomcat

From the tomcat configuration file, we can see th...

Vue3.0 handwriting magnifying glass effect

The effect to be achieved is: fixed zoom in twice...

Ubuntu Basic Tutorial: apt-get Command

Preface The apt-get command is a package manageme...

Solution to nginx hiding version number and WEB server information

Nginx can not only hide version information, but ...

jQuery implements the function of adding and deleting employee information

This article shares the specific code of jQuery t...

Implementation of Nginx operation response header information

Prerequisite: You need to compile the ngx_http_he...

Common shell script commands and related knowledge under Linux

Table of contents 1. Some points to remember 1. V...

Detailed explanation of adding click event in echarts tooltip in Vue

Table of contents need Workaround 1. Set tooltip ...

MySQL Series II Multi-Instance Configuration

Tutorial Series MySQL series: Basic concepts of M...

Implementation of Vue 3.x project based on Vite2.x

Creating a Vue 3.x Project npm init @vitejs/app m...

Tips for viewing History records and adding timestamps in Linux

Tips for viewing History records and adding times...

In-depth analysis of the diff algorithm in React

Understanding of diff algorithm in React diff alg...

How to run JavaScript in Jupyter Notebook

Later, I also added how to use Jupyter Notebook i...