📜  在没有正文解析器的情况下手动解析快速应用程序中的表单数据

📅  最后修改于: 2022-05-13 01:56:51.944000             🧑  作者: Mango

在没有正文解析器的情况下手动解析快速应用程序中的表单数据

解析是指通过 HTML 表单访问用户提交的数据。当使用 'GET' 方法提交表单时,数据会附加在 'query 字符串' 中并且可以轻松访问,但是当使用 'POST' 方法提交表单时,访问这些数据有点困难,因为它们是出于安全目的进行编码。
存在一种 body-parser NPM 方法,可以很容易地解析数据,但是如果我们尝试从头开始实现这种解析方法,则涉及一些步骤。

脚步:

  • 安装 Express 包
npm install express
  • 启动快递服务器(设置应用监听器)
app.listen(PORT, callback)
  • 为“POST”表单提交创建路由并设置中间件函数调用
app.post(path, middleware, callback)
  • 创建中间件解析函数
    • 超出编码的表单数据 aap.on() 方法。
    • 使用 decodeURIComponent() 方法将编码数据转换为字符串。
    • 创建用户提交数据的对象并将其分配给请求对象的 req.body。

示例 1:此示例创建一个登录表单。

文件:loginForm.ejs

HTML


 

    Form data parsing

 

    
        
                         
                             
        
          
                           
                             
        
          
                     
    
 


Javascript
// Installing package
const express = require('express')
const path = require('path')
const app = express()
 
const PORT = process.env.PORT || 3000
 
// Middleware function
const parseData = (req, res, next) => {
    if (req.method === 'POST') {
        const formData = {}
        req.on('data', data => {
 
            // Decode and parse data
            const parsedData =
                decodeURIComponent(data).split('&')
 
            for (let data of parsedData) {
 
                decodedData = decodeURIComponent(
                        data.replace(/\+/g, '%20'))
 
                const [key, value] =
                        decodedData.split('=')
 
                // Accumulate submitted
                // data in an object
                formData[key] = value
            }
 
            // Attach form data in request object
            req.body = formData
            next()
        })
    } else {
        next()
    }
}
 
// View engine setup
app.set("views", path.join(__dirname))
app.set("view engine", "ejs")
 
// Render Login form page
app.get('/', (req, res) => {
    res.render('loginForm')
})
 
// Creating Post Route for login
app.post('/information', parseData, (req, res) => {
 
    // Retrieve form data from request object
    const data = req.body
    const { username, password } = data
 
    //Render information in the page
    res.send(`
     
 

Login Information collected!

        
      Username : ${username}     
    
      Password : ${password}     
  `) })   // Setting up listener app.listen(PORT, () => {     console.log(`Server start on port ${PORT}`) })


HTML


 

    Form data parsing

 

    
        
                         
                             
        
          
                         
                             
        
          
                         
                             
        
          
                         
                             
        
          
                     
          
                     
    
 


Javascript
// Installing package
const express = require('express')
const path = require('path')
const app = express()
 
const PORT = process.env.PORT || 3000
 
// Middleware function
const parseData = (req, res, next) => {
    if (req.method === 'POST') {
        const formData = {}
        req.on('data', data => {
 
            // Decode and parse data
            const parsedData =
                decodeURIComponent(data).split('&')
 
            for (let data of parsedData) {
 
                decodedData = decodeURIComponent(
                        data.replace(/\+/g, '%20'))
 
                const [key, value]
                    = decodedData.split('=')
 
                // Accumulate submitted data
                // in an object
                formData[key] = value
            }
 
            // Attach form data in request object
            req.body = formData
            next()
        })
    } else {
        next()
    }
}
 
// View engine setup
app.set("views", path.join(__dirname))
app.set("view engine", "ejs")
 
// Render Login form page
app.get('/', (req, res) => {
    res.render('registrationForm')
})
 
// Creating Post Route for login
app.post('/information', parseData, (req, res) => {
 
    // Retrieve form data from request object
    const data = req.body
    const { username,
        email,
        password,
        confirmPassword,
        sex,
    } = data
 
    // Printing fetched data in
    // developer's console
    console.log(data)
})
 
// Setting up listener
app.listen(PORT, () => {
    console.log(`Server start on port ${PORT}`)
})


文件:index.js

Javascript

// Installing package
const express = require('express')
const path = require('path')
const app = express()
 
const PORT = process.env.PORT || 3000
 
// Middleware function
const parseData = (req, res, next) => {
    if (req.method === 'POST') {
        const formData = {}
        req.on('data', data => {
 
            // Decode and parse data
            const parsedData =
                decodeURIComponent(data).split('&')
 
            for (let data of parsedData) {
 
                decodedData = decodeURIComponent(
                        data.replace(/\+/g, '%20'))
 
                const [key, value] =
                        decodedData.split('=')
 
                // Accumulate submitted
                // data in an object
                formData[key] = value
            }
 
            // Attach form data in request object
            req.body = formData
            next()
        })
    } else {
        next()
    }
}
 
// View engine setup
app.set("views", path.join(__dirname))
app.set("view engine", "ejs")
 
// Render Login form page
app.get('/', (req, res) => {
    res.render('loginForm')
})
 
// Creating Post Route for login
app.post('/information', parseData, (req, res) => {
 
    // Retrieve form data from request object
    const data = req.body
    const { username, password } = data
 
    //Render information in the page
    res.send(`
     
 

Login Information collected!

        
      Username : ${username}     
    
      Password : ${password}     
  `) })   // Setting up listener app.listen(PORT, () => {     console.log(`Server start on port ${PORT}`) })

输出:

  • 登录表格:

  • 获取的登录信息:

示例 2:此示例创建一个注册表单。

文件: registrationForm.ejs

HTML



 

    Form data parsing

 

    
        
                         
                             
        
          
                         
                             
        
          
                         
                             
        
          
                         
                             
        
          
                     
          
                     
    
 

文件: index.js

Javascript

// Installing package
const express = require('express')
const path = require('path')
const app = express()
 
const PORT = process.env.PORT || 3000
 
// Middleware function
const parseData = (req, res, next) => {
    if (req.method === 'POST') {
        const formData = {}
        req.on('data', data => {
 
            // Decode and parse data
            const parsedData =
                decodeURIComponent(data).split('&')
 
            for (let data of parsedData) {
 
                decodedData = decodeURIComponent(
                        data.replace(/\+/g, '%20'))
 
                const [key, value]
                    = decodedData.split('=')
 
                // Accumulate submitted data
                // in an object
                formData[key] = value
            }
 
            // Attach form data in request object
            req.body = formData
            next()
        })
    } else {
        next()
    }
}
 
// View engine setup
app.set("views", path.join(__dirname))
app.set("view engine", "ejs")
 
// Render Login form page
app.get('/', (req, res) => {
    res.render('registrationForm')
})
 
// Creating Post Route for login
app.post('/information', parseData, (req, res) => {
 
    // Retrieve form data from request object
    const data = req.body
    const { username,
        email,
        password,
        confirmPassword,
        sex,
    } = data
 
    // Printing fetched data in
    // developer's console
    console.log(data)
})
 
// Setting up listener
app.listen(PORT, () => {
    console.log(`Server start on port ${PORT}`)
})

输出:

  • 报名表格:

  • 获取注册数据并在控制台上打印: