1. Why learn node.js
- understand nodejs
- Understand the backend (read local files, connect to databases, respond to requests)
- Understand the api interface document
2. Check whether there is a node and whether mysql is installed successfully
node -v
- If this happens
- Proceed as follows. Find the task manager through ctrl+alt+delete, find mysql in the service and click start
- Then perform the following operations mysql -u root -p enter the password
3. Initialize the project
- Change to the project directory
npm init -y
4. Using third-party modules
- install module
npm i axios -S
- import module
const axios = require("axios")
- use modules
axios.get(url).then(res=>{})
5. Using custom modules
- define module utils.js
module.exports ={max(){},randomStr(){}}
- Import and use (Method 1)
Importconst utils = require('./utils.js')
and useutils.max() utils.randomStr()
Import and use (Method 2)
Import andconst {max,randomStr} = require(' ./utils.js')
usemax() randomStr()
- quick export
exports.say = function(){console.log("到结婚了年龄吗?")}
6. Project running
- configuration command
package.json->script
"serve":"node main.js"
npm run serve
- cmd
1. Enter the project directory
2.node main/js
7. mysql command
- query select
SELECT * FROM `feedback ` WHERE 1;
//指定列查询
SELECT 'msg ',' name' `FROM `feedback` WHERE 1;
//添加查询条件
SELECT * FROM feedback WHERE name='小曾;
//查询msg中包含山的元素 %代表是任意字符
SELECT * FROM `feedback` where msg like '%山%;
//_代表任意一个字符串
select* from feedback where msg like '山_有%';
//desc按时间排序降序
select * from feedback where 1 order by `datetime ' desc;
//查询偏移2个截取3行
select * from feedback where 1 order by `datetime ' desc limit2,3;
- increase insert into
- delete delete
- modify update
8.node operation sql⭐
-
Install
npm i mysql -S
-
import
const mysql = require("mysql")
-
create connection
const conn = mysql.createConnect({ host:"localhost", user:"root", password:"", database:"feed"})
-
Connect to the database
conn.connect(function(err){if(!err){console.log("数据库连接成功")}})
Navicate is needed to connect to the database ⭐
1. Open the connection and find mysql
2. Double-click to open the message board after entering the password successfully.
3. Double-click to open the message board after successfully entering the password.
-
define sql
var sql = "select * from feedback where 1”
-
execute sql
conn.query(sql,function(err,result){if(!err){console.log(result)}})
-
disconnect database
conn.end(function(){console.log("数据库己断开")})
9. Built-in server creation ⭐
1. Import http const http = require("http")
2. Create service
const server = http.createServer(function(req,res){ //req请求的数据 //res响应的数据 res.statusCode = 200; //响应码 res.setHeader("Content-Type","application/json") //响应类型 res.end(
{} )//返回的数据 })
3. Listen port
server.listen(8888,function(){ console.log("localhost:8888 启动") })