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

Vue implements two routing permission control methods

Table of contents Method 1: Routing meta informat...

Detailed analysis of the MySQL slow log opening method and storage format

In development projects, we can monitor SQL with ...

Detailed explanation of the buffer pool in MySQL

Everyone knows that data in MySQL needs to be wri...

js uses FileReader to read local files or blobs

Table of contents FileReader reads local files or...

Solution to Chinese garbled characters when operating MySQL database in CMD

I searched on Baidu. . Some people say to use the...

Two tools for splitting the screen in the Linux command line terminal

Here are two terminal split screen tools: screen ...

How to install Elasticsearch7.6 cluster in docker and set password

Table of contents Some basic configuration About ...

JavaScript to achieve lottery effect

This article shares the specific code of JavaScri...

Methods and steps for Etcd distributed deployment based on Docker

1. Environmental Preparation 1.1 Basic Environmen...

Nginx reverse proxy configuration to remove prefix case tutorial

When using nginx as a reverse proxy, you can simp...

A good way to improve your design skills

So-called talent (left brain and right brain) Tha...

How to separate static and dynamic state by combining Apache with Tomcat

Experimental environment Apache and Tomcat are bo...

Detailed explanation of MySQL InnoDB index extension

Index extension: InnoDB automatically extends eac...