Essays: front and back end interaction

In data interaction, the front end will initiate an ajax request. The request method is as follows:\

type:'post',  //  Request mode type
url:' ', / / the api interface address corresponding to the request
data:{name:'zs'},  //Submitted data
success:function(res){  // Callback function requested

  The back-end api will respond to the front-end request as follows:

const express = require('express')  //Import express server module
const mysql = require('mysql')  //Import mysql database module
const cors = require('cors')  //Import cross domain modules
const app = express()  // Instantiate a server object
const db = mysql.createPool({  //Create a database connection instance object
  host: '',//Address to connect to the database
  user: 'root', // Login account name to connect to the database
  password: 'admin123',  //Password to connect to the database
  database: 'my_db_01',  //Name of the connection database
app.use(express.urlencoded({extended:false})) // Mounting data transcoding Middleware
app.use(cors())  // Mount cross domain Middleware'/user',(req,res)=>{ // Listen to the post request whose api interface is / user (compared with js click event listening)
db.query('update user set ? where id = ?',[req.body,,(err,data)=>{  //Fill the fields in the query statement by splicing? In the placeholder, multiple fields need to be written in an array in order. The data sent by the client will be mounted in the body attribute of req and can be obtained through req.body. In addition, req.query obtains the request field of get request
if(err){return res.send({  //If the database connection fails, you need to prompt the user
status:1, // 0 and 1 have no specific requirements, but personal settings represent success or failure
if(data.affectedRows != 1){
res.send({  //If the returned affected value of the database parameter is not 1 when operating the database, it indicates that the operation has failed and the user needs to be prompted
message:'request was aborted'
res.send({ //After eliminating all possible failures, the server response value for successful completion is sent to the client
message:'Request succeeded'
app.listen(8080,()=>{ //Start the server
console.log('Start successful')
//So far, a simple server api interface has been written. In fact, there are many places that can be improved and optimized. Some, such as local middleware for format verification, modular processing, etc., are not used, but it is enough to explain the principle of front-end and back-end interaction

Summary: after learning this part of knowledge, I found that the original post request and get request do not necessarily represent writing data to the server and requesting data from the server. Their specific functions are determined according to the operation methods written therein, and the decision-making method of using them is what data to submit to the server, For example, is it the data of req.body or the request field of req.query.
The client submits the data to the server. After processing, the server returns the response value to the client through res.send(). The client receives and returns the response value through the res parameter of the success function

1. For the res.send() part with high repetition, a unified processing middleware can be mounted in the js module for final integration operation (temporarily called app.js). The code is as follows:

app.use(function (req, res, next) {  //The next callback function unique to ordinary middleware is used to realize data flow to the next middleware or route = function (err, status = 1) {// status = 0 means success; status = 1 means failure; By default, the value of status is set to 1 to facilitate failure handling
      // state
      // State description to determine whether err is an error object or a string
      message: err instanceof Error ? err.message : err,

Note: this method is to attach a method named cc to res, where the formal parameter err represents the message content returned by res.send(), and status represents the status code. There are three main methods:
(1) res.send(err). In the if(err) {} statement to judge whether the database connection is successful, err passes in an error object, so status: 1 and message: err.message are output through
(2) res.send('Send failed '). In the if (data. Affectedrows! = 1) {} statement, the output is status: 1 and message:' send failed '
(3) res.send('processing succeeded ', 0). In, the output is status:0,message:' sending succeeded '
In this way, the code of routing processing function is simplified

2. Use of token

(1) In the js file of the login module, write the following code:

const jwt = require('jsonwebtoken')// Import the JSON webtoken package to generate the Token string
const config = require('../config') //Import a configuration file dedicated to sharing encryption and resolving and restoring token keys outward
//There is only one line of code: module.exports = {jwtSecretKey:'aaa'}
const tokenStr = jwt.sign(user, config.jwtSecretKey, { //Generate token string
  expiresIn: '10h', // The valid period of the token is 10 hours
res.send({  // The code here cannot be replaced by because there are multiple token parameters
  status: 0,
  message: 'Login succeeded!',
  token: 'Bearer ' + tokenStr, // In order to facilitate the client to use Token, the prefix Bearer is directly spliced on the server
///The above is the code of the login module js file

(2) In the integration module app.js, the corresponding parsing middleware needs to be mounted before registering the route
The code is as follows:

const config = require('./config')// Import profile
const expressJWT = require('express-jwt')// Middleware for parsing token
app.use(expressJWT({ secret: config.jwtSecretKey }).unless({ path: [/^\/api\//]}) / / use. Unless ({path: [/ ^ \ / API \ / /]}) to specify which interfaces do not require Token authentication

(3) In the error level middleware of app.js, you need to capture the error of token authentication failure to avoid collapse caused by authentication failure

app.use(function (err, req, res, next) {// Error Middleware
  // Code for other error capture is omitted here
  if ( === 'UnauthorizedError') return'Identity authentication failed!') // Error capturing authentication failure

3. In the actual development, it also includes the local middleware module for format verification and the bcryptjs module for storing the garbled code after converting the user password to the encrypted state into the database, which will not be listed here

Tags: Javascript node.js Vue.js

Posted on Tue, 23 Nov 2021 09:34:12 -0500 by MasterACE14