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

Tutorial on installing MySQL 5.6 on CentOS 6.5

1. Download the RPM package corresponding to Linu...

Detailed explanation of various types of image formats such as JPG, GIF and PNG

Everyone knows that images on web pages are genera...

How to use docker to deploy Django technology stack project

With the popularity and maturity of Docker, it ha...

Form submission refresh page does not jump source code design

1. Design source code Copy code The code is as fol...

JavaScript removes unnecessary properties of an object

Table of contents Example Method 1: delete Method...

Detailed configuration of Nginx supporting both Http and Https

It is almost a standard feature for websites nowa...

Detailed discussion of memory and variable storage in JS

Table of contents Preface JS Magic Number Storing...

A brief introduction to MySQL InnoDB ReplicaSet

Table of contents 01 Introduction to InnoDB Repli...

Professional and non-professional web design

First of all, the formation of web page style main...

Use Docker to run multiple PHP versions on the server

PHP7 has been out for quite some time, and it is ...

Use the CSS border-radius property to set the arc

Phenomenon: Change the div into a circle, ellipse...

IIS7~IIS8.5 delete or modify the server protocol header Server

Requirements: Remove HTTP response headers in IIS...