Connect to mysql, add, delete, change, check operation
1. Data connection
- Connecting to the mysql database in Node requires the installation of a third-party plug-in package
- Run the command:
npm i mysql -S
, wait for completion
- Run the command:
- You can download a phpStudy service that simulates mysql, open the mysql client, create a table, and then create an HTTP service to connect to the database
- Import the mysql module and connect to the database through createConnection
// import mysql module const mysql = require("mysql"); Const conn= mysql.createconnection ({host:'localhost',// domain name or IP address user:"root",// created mysql database user name Password :'root', // create mysql database password database:'mysql_001'})Copy the code
2, data increase, delete, change and check, NODE SQL statements and SQL statements in other languages may not be different in individual places, we must check more documents when we use
- The query
- Select queries
select * from users
* stands for full query, and users is the name of the created table being queried
- Select queries
Conn.query (' SQL statement to execute ',(err,resule)=>{} method to execute SQL statements)
const sqlStr='select * from users'
conn.query(sqlStr,(err,res) = >{
if(err) return console.log('Failed to get data'+ err.message);
console.log(res);
})
Copy the code
- The new statement
- Insert to insert
insert into users set?
Insert is an insert, users is the table being operated on,? Is a placeholder for inserting data when executing a statement?
- Insert to insert
/ / new
const users={usename:"Xiaojuan".age:22.gender:'woman'}
const sqlStr2='insert into users set? '
conn.query(sqlStr2,users,(err,res) = >{
if(err) return console.log('Error adding data'+err.message);
console.log(res);
})
Copy the code
- Modify the statement
- The update to update
update users set ? where id=?
Is it used anywhere in Node that needs to be queried or replaced? Instead of where followed by the query criteria
- The update to update
/ / modify
const users={id:2.usename:"Little beauty".age:22.gender:'woman'}
const sqlStr3='update users set ? where id=? '
// If the SQL statement contains more than one? Placeholder, the second argument must
// Pass an array. Each item in the array must be the same as the SQL statement? On the corresponding
conn.query(sqlStr3,[users,users.id],(err,res) = >{
if(err) return console.log('Error modifying data'+err.message);
console.log(res);
})
Copy the code
- Delete statements
- Delete delete
delete from users where id=?
Delete delete, users is the table being operated on,? The id value to be deleted
- Delete delete
/ / delete
const sqlStr4='delete from users where id=? '
conn.query(sqlStr4,5.(err,res) = >{
if(err) return console.log('Error deleting data'+err.message);
console.log(res);
})
Copy the code
Chapter two: module loading mechanism
- Loading from cache is preferred
- When a module is required for the first time, the code in the module will be executed. When the same module is loaded for the second time, it will first look up the module from the cache to see if there is such a module!
- Benefits: improve the loading speed of modules; You don’t need to re-execute and load the module every time!
- The loading mechanism of core modules
- First look up the cache; If not, load the core module again.
- Loading mechanism of user module
- First look up the cache;
- If not in the cache, try to load the user module;
- If the suffix is omitted when loading the user module, then:
- First, look up exactly by the given name
- Second, try to load a file with the.js suffix
- If there is no.js file, try loading a.json file
- If there is no.json file, try loading the.node ending file
- Js -> index.json -> index.node
- Loading mechanism for third-party modules
- Start by looking for the node_modules folder in the project root
- In the node_modules folder, look for the folder associated with the module
- Find the package.json file in the corresponding folder
- Find the main property in package.json (specifies the entry file for the module)
- If the main attribute is found and the file path specified by the main attribute exists, try to load the specified file module
- If there is no main attribute, or the file corresponding to the main attribute does not exist, or there is no package.json, then attempts will be made to load index.js, index.json, and index.node in sequence.
- If there is no file associated with index, or the module folder is not specified, or the node_modules folder is not found in the current project root directory, then go up to the node_modules directory and find the same rules as above.
- Finally, if the corresponding module cannot be found in the root directory of the disk where the project resides, an error is reported: cannot find module ***
Some forms of obtaining parameters in Express
- To obtain
? id=10&name=zs
Query parameters in:- Direct use of
req.query
Parameters can be obtained; - Note: The Express framework directly parses parameters passed in the query string in the URL address bar, so you only need to use them
req.query
Directly get the parameters of the query string in the URL;
- Direct use of
- Get path parameters from the URL address:
- Suppose the background route is
app.get('/user/:id/:name', (req, res) => {})
- Suppose the client browser requests the URL:
http://127.0.0.1:3001/user/10/zs
- Direct use of
req.params
You can get the parameters passed from the URL address;
- Suppose the background route is
- Get submitted data from the POST form:
- With the aid of
body-parser
To parse form data - Installation:
npm i body-parser -S
- Import:
const bodyParser = require('body-parser')
- Register middleware:
app.use(bodyParser.urlencoded({ extended: false }))
- Using parsed data:
req.body
To access parsed data
- With the aid of
Chapter four: Realizing the cross-domain solution of the front and back end separated projects
- Different port numbers between the front end and back end cause cross-domain
- Jsonp and COR are good at solving cross-domain problems
- Jsonp: Dynamically create script tags;
- JSONP is not sending Ajax requests
- Post requests are not supported;
- CORS in Chinese means cross-domain resource sharing, which requires CORS configuration on the server.
- CORS sends real Ajax requests
- CORS supports cross-domain Ajax
- If you want to enable CORS cross-domain resource sharing, the key lies in the server side. As long as the server supports CORS cross-domain resource sharing, the browser must be able to access the CORS interface normally. In addition, the client sends Ajax as if it were normal, with no code changes;
- For Node, if you want to enable CORS cross-domain communication, you only need to install the CORS module.
- Jsonp: Dynamically create script tags;
- Jsonp and COR are good at solving cross-domain problems
Install cORS: NPM install cors -s //2. Const cors=require('cors') //3 Register middleware app.use(CORS ())Copy the code