当前位置:网站首页>Node (express) implements interfaces such as adding, deleting, modifying, and paging

Node (express) implements interfaces such as adding, deleting, modifying, and paging

2022-06-10 20:38:00 Rulyc

https://blog.csdn.net/CuiCui_web/article/details/107042226 This article describes how to connect to the database , I don't want to make too many introductions here .

1、 First we install two packages , One is to solve cross domain problems , The other one is node in post Request parameters will not be available , You need plug-ins

npm i cors --save  Solving cross domain problems 
npm i body-parser --save post Request parameters 

2、 stay app.js Introduction in

const bodyParser=require('body-parser');
const cors = require('cors'); //  Solving cross domain problems 
var app = express();

app.use(cors()); //  Solving cross domain problems 
app.use( bodyParser.urlencoded({
    
  extended:false
}) );

3、 Write the interface in the interface file , Such as index.js In this paper, , Get ready

var express = require('express');
var router = express.Router();
const connection = require('../db/database')
connection.getConnection(function (err,connection) {
     //  Use connection pool 
  if(err){
    
    console.log(' And MySQL Database connection failed !');
    console.log(' The error message is :' + err);
  }
  else{
    
    console.log(' And MsSQL Database connection established successfully !');
  }
});

//  Insert the interface code in the middle 
.........

module.exports = router;

…/db/database Is the configuration of the database
 Insert picture description here

Now officially index.js Write interfaces in

Query interface get request ( No paging and parameters )

router.get('/demo', (req, res, next)=> {
    
  connection.query('SELECT * FROM student_info', function(err,result){
    
    // resolve();
    console.log(result)
    res.send(result);
  });
});

We can type... In the browser http://localhost:3000/demo To view the

Query interface post request ( With parameters and paging conditions )

router.post('/demo', (req, res, next)=> {
    
  console.log(req.body)
  let name = req.body.name
  let pageSize = req.body.pageSize //  Page size 
  let pageCurrent = req.body.pageCurrent //  The current page 
  let start=(pageCurrent-1)*pageSize; //  The starting position 
  connection.query(`SELECT * FROM student_info WHERE name LIKE '%${
      name}%' LIMIT ${
      start},${
      pageSize}`,function(err,result){
    
    if(err) throw err;
    let list = result
    connection.query(`SELECT COUNT(*) AS total FROM student_info`,function(err,result1){
    
      if(err) throw err;
      console.log(result1[0].total)
      let obj = {
    
        pageSize: pageSize,
        pageCurrent: pageCurrent,
        total:result1[0].total,
        list: list
      }

      res.send(obj);
    })
  })
});

Be careful , There is a hole ,sql Data cannot be obtained after execution , Because I'm here sql The operation expression is written in SELECT * FROM student_info WHERE name LIKE '%${name}%' LIMIT ${(pageCurrent-1)}*${pageSize},${pageSize}, Lead to undefined. Bring up the operation ,let start=(pageCurrent-1)*pageSize; // The starting position , Just fine

The new data get request

router.get('/demo_add', function(req, res, next) {
    
  let params = req.query;
  if(params){
    
    console.log(params.name,params.age,params.address,params.id)
    params.id = 'NULL';
    console.log(params)
    connection.query(`INSERT INTO student_info VALUES(${
      params.name},${
      params.age},${
      params.address},${
      params.id});`, function(err,result){
    
      if(err){
    
        res.send(" Add failed "+err);
      }else {
    
        res.send(" Added successfully ");
      }
    });
  }
});

The new data post request

router.post('/demo_add',(req, res, next)=> {
    
  let params = req.body.val;
  console.log(params)
  if(params){
    
    params.id = 'NULL';
    connection.query(`INSERT INTO student_info VALUES('${
      params.name}',${
      params.age},'${
      params.address}',${
      params.id});`, function(err,result){
    
      if(err){
    
        res.send(" Add failed "+err);
      }else {
    
        console.log(result,' newly added ')
        res.send(" Added successfully ");
      }
    });
  }
});

Modifying data post request

router.post('/demo_update', (req, res, next)=> {
    
  let params = req.body.val;
  if(params){
    
    connection.query(`UPDATE student_info SET name='${
      params.name}',age=${
      params.age},address='${
      params.address}' WHERE id=${
      params.id} ;`, function(err,result){
    
      if(err){
    
        res.send(" Modification failed "+err);
      }else {
    
        console.log(result,' modify ')
        res.send(" Modification successful ");
      }
    });
  }
});

Delete interface delete

router.delete('/demo_del',(req, res, next)=> {
    
  let params = req.body.id;
  if(params){
    
    connection.query(`DELETE FROM student_info WHERE id = ${
      params} ;`, function(err,result){
    
      if(err){
    
        res.send(" Delete failed "+err);
      }else {
    
        console.log(result,' Delete ')
        res.send(" Delete successful ");
      }
    });
  }
})

The front-end code of this article is shown in react+element To write , The article links https://blog.csdn.net/CuiCui_web/article/details/107108677

原网站

版权声明
本文为[Rulyc]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/161/202206101932002480.html