How to get the get and post parameters in the Express framework

get parameters

Express is a web application development framework based on node platform. It provides a series of powerful features to help you create various web applications.
It enables us to create website applications with more concise code.

Before learning how Express gets the get request, let's take a look at the Node's native get request parameters

// Module for creating a web server
const http = require('http')
// Process url address
const url = require('url')
// Create server
const app = http.createServer()
// Add events to the server
app.on('request', (req, res) => {
  // Respond to clients
  // response message
  // Set http status code 200, request sent successfully 300, redirect 404, requested resource not found 400, client request syntax error 500, server error
  res.writeHead(200, {
    // Set the response content type text/plain for plain text text/html for html file text/css for css file application/javascript for js file image/jpeg for picture file application/json for json format
    'content-type': 'text/html'
  })
  console.log(req.url);
 // The parse property converts the get parameter to an object
  let { query, pathname } = url.parse(req.url, true);
  console.log(query);
  console.log(query.name);
  console.log(query.age);
  console.log(pathname);

  if (pathname == '/index' || pathname == '/') {
    res.end('<h2>Welcome to index</h2>')
  } else if (pathname == '/user' || pathname == '/') {
    res.end('<h2>Welcome to user</h2>')
  } else {
    res.end('not found')  
  }

})
// After the server is created, be sure to listen to the window
app.listen(8080);
console.log('Web server started successfully');


The native node needs to introduce a url module to parse the url request address to obtain the get parameters

Express get parameters
The Express framework adds a query attribute to the request parameter req, using req Query to obtain the get parameter. The framework will convert the get parameter into an object return

const express = require('express')

const app = express()
app.get('/',(req,res)=>{
  console.log(req.query);
})
app.listen(3000)
console.log('success');

Acquisition of post parameters

First review the Post parameter acquisition of NodeJs
post.html

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <form method="post" action="http://localhost:8080">
    <input type="text" name="username">
    <input type="password" name="password">
    <input type="submit" name="submit">
  </form>
</body>

</html>

post.js

// Module for creating a web server
const http = require('http')
// Create server
const app = http.createServer()
// Processing request parameter module
const querystring = require('querystring')
// Add events to the server
app.on('request', (req, res) => {
  // The post parameter is received by means of events. When the data request parameter is passed, the end parameter is completed
  let postParams = '';
  // param is the passed value
  req.on('data', params => {
    postParams += params
  })
  req.on('end', () => {
    // Convert string to object
    const pParams = querystring.parse(postParams)
    console.log(pParams);
  })
  // The server must respond to every request of the client, otherwise the client will be in a waiting state
  res.end('<h1>ok</h1>')
})
app.listen(8080);
console.log('Web server started successfully');

Since the post parameter is not stored in the address bar, it cannot be passed through req URL, we introduced the querystring module to handle the request parameters
The post parameter is processed in two stages. The first stage is to obtain the passed value, and the second stage uses the parse attribute to convert the string into an object

Express get post parameter
In order to make the framework itself smaller, Express encapsulates many packages with different functions, which are introduced when you use it
If you are currently receiving post parameters, you need to use the third-party package body parser

post.html

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <form action="http://localhost:3000/add" method="post">
    <input type="text" name="username">
    <input type="password" name="password" id="">
    <input type="submit" value="Submit">
  </form>
</body>

</html>

post.js

const express = require('express')

const bodyParser = require('body-parser')
const app = express()
app.use(bodyParser.urlencoded({extended:false}))
app.post('/add',(req,res)=>{
  res.send(req.body)
})
app.listen(3000)


Use app The use middleware intercepts all requests and calls the urlencoded method under the bodyParser module object to process the request. Urlencoded will judge whether there are request parameters in the current request. If so, it will receive the request parameters and convert them into object types. Then add the body attribute to the req request object and pass the value of the request parameters to the body attribute, Call the next method inside the method and hand over the request control to the next middleware

When extended is false, the querystring third-party module is used for processing. The default value is
When extended is true, qs is used to process the request parameters

Keywords: Javascript node.js http

Added by bala_god on Fri, 17 Dec 2021 03:15:25 +0200