This is the third day of my participation in the November Gwen Challenge. Check out the details: the last Gwen Challenge 2021

As a front-end, you can’t help but interface with the back end, looking at the back end like “you don’t understand” and wishing you could write a socket in his face.

Of course, this article is just the beginning


In this blog post, we will take a look at how to write backend services using nodeJS

First, the hierarchical structure of the project is as follows:

  • Db writes operations to the database
  • Customer is the database operation code of the customer module
  • Pool is a connection pool that creates connection objects
  • The router writes routes. You can perform different operations based on the path. In this example, express routes are used. Write directly export, then use the words directly import, and application can be
  • Index is the main file that creates the server object, starts the server, etc
  • Package is the configuration file

Pool = pool = pool = pool = pool = pool = pool

const mysql = require('mysql')
 
// Create a connection pool object
const pool = mysql.createPool({
    host:'127.0.0.1'.port:3306.user:'root'.password:'root'.database:'test'
})
 
// Export the connection pool object
module.exports = {
    pool
}
Copy the code

Install the mysql module first and then import it

You then create a link pool object to connect to the database

  • Host: indicates the host name
  • Port: indicates the port number
  • User: indicates the user name
  • Password: password
  • -Leonard: The database.

Finally, the link pool object is exported

2. Customer file in db folder, code as follows:

// Encapsulate method
// Import the connection pool object
const {pool} = require('./pool')
 
/ / query
let findAll = (handle) = >{
    // Get the connection object. The second parameter represents the connection object
    pool.getConnection((err,connection) = >{
        if(err) throw err;
        let sql = 'select * from account_customer'
        connection.query(sql,[],(err,result) = >{
            if(err) throw err;
            handle(result)
            // Release the connection object to the connection pool
            connection.release()
        })
    })
}
// Query by customer name
 
// Batch delete
 
// Get customer information by id
let findById = (handle,id) = >{
    pool.getConnection((err,connection) = >{
        if(err) throw err;
        let sql = 'select * from account_customer where id=? '
        connection.query(sql,[id],(err,result) = >{
            if(err) throw err;
            handle(result)
            connection.release()
        })
    })
}
 
// Delete customer information by id
let deleteById = (handle,id) = >{
    pool.getConnection((err,connection) = >{
        if(err) throw err;
        let sql = 'delete from account_customer where id=? '
        connection.query(sql,[id],(err,result) = >{
            if(err) throw err;
            handle(result)
            connection.release()
        })
    })
}
 
 
// Save or update customer information
let saveOrUpdate = (handle,obj) = >{
    pool.getConnection((err,connection) = >{
        if(err) throw err;
        let sql = ' '
        // An id is required for an update
        if(obj.id){
            // If there is an ID, it is an update
            sql = 'update account_customer set description=? ,money=? ,type=? where id=? '
        }else{
            / / save the SQL
            sql = 'insert into account_customer(description,money,type) values(? ,? ,?) '
        }
 
        connection.query(sql,[obj.description,obj.money,obj.type,obj.id],(err,result) = >{
            if(err) throw err;
            handle(result)
            connection.release()
        })
    })
}
 
module.exports = {
    findAll,
    findById,
    deleteById,
    saveOrUpdate
}
Copy the code

Code notes to write very clear, here is not to do a detailed description, what do not understand, can be small private letter oh. Simply put, in fact, is to execute SQL statements, add, delete, change and check, if there is no SQL basis, then you can go to understand the basic SQL statement oh

 

3. Then look at the customer file in the router. The code is as follows:

const express = require('express')
let customerDB = require('.. /db/customer')
// Create a route
let customer = express.Router()
 
// Set the route. Different interfaces implement different functions
// Query all customer information
customer.get('/findAll'.(req,res) = >{
    // Call the dao layer methods to access the database
    customerDB.findAll((result) = >{
        res.send(result)
    })
})
 
customer.get('/findById'.(req,res) = >{
    customerDB.findById((result) = >{
        res.send(result)
    },req.query.id)
})
 
customer.get('/deleteById'.(req,res) = >{
    customerDB.deleteById((result) = >{
        res.send(result)
    },req.query.id)
})
 
customer.post('/saveOrUpdate'.(req,res) = >{
    // console.log(req.body)
    customerDB.saveOrUpdate((result) = >{
        res.send('Saved successfully')
    },req.body)
})
 
module.exports = customer
Copy the code

This is mainly to filter the path, according to different paths to call different methods, so as to execute different SQL, query the data, and then return to the page. That’s it, request the interface, and then the corresponding data. The interface and SQL are in a one-to-one correspondence. The route is exported and used in inde.js.

 

3. Take a look at the index.js file:

const express = require('express')
const bodyParser = require('body-parser')
 
// Route object
const customer = require('./router/customer')
 
// let customer = express.Router()
// Create an application
let app = express()
 
app.use(bodyParser.urlencoded({extended:true}))
 
// Use interceptor
app.all(The '*'.(req,res,next) = >{
    res.set({
        "Access-Control-Allow-Origin":"*"."Content-Type":"text/plain; charset=utf-8"
    })
    next()
})
 
// Use the imported routing object
app.use(customer)
 
// Start the server and set the port
app.listen(3000.() = >{
    console.log('3000 port startup...... ')})Copy the code

In the index file to import route objects, and to use the app. Use to use import route objects inside the interceptor points the recognition of encoding, and solved the problems of cross-domain, * on behalf of all the domain by request can be through, if you want to configure individual domain can access, so here it is equivalent to set a white list! Just replace the * with the domain name

4. Finally take a look at the configuration in package.json to see which dependencies to install

I’ve always wanted to try to build a file server using Node, so let’s see

First of all, when we do file upload, we often use the file server. On the front end, we upload the data to the file server, and the file server returns us an access address for the files you upload

That is to say, the file server must first read the data uploaded by our front end, and then, the file needs to be stored in the server’s specified directory, and finally the storage address is stored in the database and returned to the front end

After understanding the principle, do train of thought is more clear

The preparatory work

1. Ensure that the Node environment is available

  1. Create a folder “node” (any name), and under this folder create files “serve.js” (server file), “index.html” (front-end test file), and “uploads” (for front-end uploads).

  2. Open the console in the Node folder and execute NPM init, which generates a package.json file, the configuration file

Let’s start with the server file refinement

The specific code is shown below, the annotation is very detailed oh

// Use NPM install to install Express and formidable
// Make sure you have a uploads folder at the same level as the current one
var Express = require('express');
var App = Express();
var Path = require('path');
var Formidable = require('formidable');
var FS = require('fs');
 
App.all(The '*'.function (req, res, next) {
  // Resolve cross-domain
  res.header('Access-Control-Allow-Origin'.The '*');
  // Set the corresponding header data
  res.header('Access-Control-Allow-Headers'.'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
  // Set the receiving method
  res.header('Access-Control-Allow-Methods'.'PUT, POST, GET, DELETE, OPTIONS');
  next();
});
 
App.post('/upload'.function(req, res){
  // Create a form object
    var form = new Formidable.IncomingForm();
    // With this function enabled, when the form.parse() method is called, the files parameter of the callback function will be an array of files, and each member of the array is a file object. This function requires multiple features in HTML5.
    form.multiples = true;
    // Set the current uploaded file to the /uploads folder
    form.uploadDir = Path.join(__dirname, '/uploads');
    var dirUrl
    // Listen for uploaded file data
    form.on('file'.function(field, file) {
        var newName = file.name;
        / / renamed
        FS.rename(file.path, Path.join(form.uploadDir,newName),function(err) {
            if(err){
                throwerr; }});// Get the storage path of the currently uploaded file
        dirUrl = Path.join(form.uploadDir,newName)
    });
    // Listen error
    form.on('error'.function(err) {
        console.log('An error: \n' + err);
    });
    // When receiving data is complete, the directory of the currently uploaded file is returned to the foreground
    form.on('end'.function() {
        res.send(dirUrl);
    });
    // Parse the data carried in the request
    form.parse(req);
  });
 
  // Start the service setting port
  var server = App.listen(1000.function(){
      console.log('Files Server listening on port 1000');
  })
Copy the code
Front-end test code

I here is the use of vue, this does not matter, only for reference, you write native can also test ha

<! DOCTYPEhtml>
<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>
  <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.9/vue.js"></script>
  <! -- Introducing styles -->
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
<! -- Introducing a component library -->
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
</head>
<body>
   <div id="main">
    <el-upload
    class="upload-demo"
    action="http://localhost:1000/upload"
  >
    <el-button size="small" type="primary">Click on the upload</el-button>
  </el-upload>
   </div>
   <script>
     new Vue({
       el:'#main'.data:{}
     })
   </script>
</body>
</html>
Copy the code

Combined with the above code, is to build a local file server, of course, I am directly a one-time return to the path of the file you uploaded, and did not store its path in the database

This step is relatively easy, after all, the path has been obtained, and the above instructions

Front end small rookie, hope can criticize correct, study together, progress ha