nodejs basis -5

routing

Tell you where to go for the front-end, mainly oriented to tell the browser where to go for the back-end, can be understood as a child service, a route is a little service (server / app), an interface processing

Configuration and Use

/routes/xx.js

// 1. 创建路由
let router = express.Router(); 

//2 路由处理响应
router.响应API(地址, 处理函数)

//3. 导出路由
module.exports = router;

/app.js main service

//安装路由
app.use('地址',router); 

/routes/xx.js

//字路由里安装路由 嵌套
router.use('地址',子router) //需要next 延续

//截获当前路由下的部分公共业务
router.all('*',当前router路由下的验证工作) //需要next 延续

Main route corresponding to the address of the root of the sub-route

Such as: app.js: /api/user~ ~ user.js:/

Such as: app.js: /api/user/add~ ~ user.js:/add

Example:

const express = require("express")
const app = express()
app.listen(3000)


app.all("*",(req,res,next)=>{
    req.title = "index.js"
    next()
})

//app.get("/api/a",require("./routes/a.js")) 报错了!

//主入口上面通过安装路由
// app.use('地址',router); 
app.use("/api/a",require("./routes/a.js"))



app.get("/reg",(req,res)=>{
    console.log("reg===>",req.title)
    res.end()
})




// app.get("/api/a/b",(req,res)=>{
//     console.log("这是index.js文件里面的/api/a/b哦....")
//     res.end()
// })

// app.get("/api/a/c",(req,res)=>{  //30行  返回json数据 前端
//     console.log("这是index.js文件里面的/api/a/c哦....")
//     res.end()
// })

a.js:

// 1. 创建路由
let express = require("express")
let router = express.Router(); 


router.all("*",(req,res,next)=>{
    req.title = "a.js"
    console.log("-----进入a.js里面的all方法了-------")
    next()
})


//2 路由处理响应
// router.响应API(地址, 处理函数)
router.get("/",(req,res,next)=>{
    console.log("这是a.js文件里面的/api/a哦....")
    res.end()
})


//通过router.use方法来去注册子路由
//当我们浏览器访问/api/a/b的时候就会进入b.js里面的/所对应的回调函数 
router.use("/b",require("./b.js"))


// /api/a/c
router.get("/c",(req,res)=>{  //30行  返回json数据 前端
    console.log("这是a.js文件里面的/api/a/c哦....",req.title)
    res.end()
})




//3. 导出路由
module.exports = router;

b.js

let express = require("express")
//创建路由
let router = express.Router()


//可以通过router.all方法实现公共业务抽离
router.all("*",(req,res,next)=>{
    req.title = "b.js文件"
    console.log("-----被b.js里面的all方法拦截了哦----")
    next()
})

//路由的响应处理
router.get("/",(req,res,next)=>{
    console.log("这是b.js文件里面的/api/a/b哦....",req.title)
    res.end()
})

// /api/a/b/b1-1
router.get("/b1-1",(req,res,next)=>{
    console.log("这是b.js文件里面的/api/a/b/b1-1哦....",req.title)
    res.end()
})


router.get("/b1-2",(req,res,next)=>{
    console.log("这是b.js文件里面的/api/a/b/b1-2哦....",req.title)
    res.end()
})


//暴露路由
module.exports = router

database

mysql

Relational databases, two-dimensional table, the child table does not exist

sql statement

Building a database

CREATE DATABASE  `2017-12-6` DEFAULT CHARACTER SET armscii8 COLLATE armscii8_general_ci;

To build the table

CREATE TABLE  `2020-12-6`.`user` (
					`name` VARCHAR( 32 ) NOT NULL ,
					`age` INT( 3 ) NOT NULL ,
					`address` VARCHAR( 128 ) NOT NULL
					) ENGINE = INNODB

increase

INSERT INTO 表 (字段列表) VALUES(值列表)
INSERT INTO user (name,age,address) VALUES('苏菲',38,'')

delete

DELETE FROM 表 WHERE 字段名=值
DELETE FROM user WHERE name='alex'

change

UPDATE 表 SET 字段名=值 WHERE 字段名=值
UPDATE user set name='sufei' WHERE name='苏菲'

check

SELECT ? FROM 表
SELECT * FROM user  查所有

Example:

//1引入mysql客户端的包
var mysql = require("mysql")
var express = require("express")
var app = express()
app.listen(3000)

//2创建库的链接
var connection = mysql.createConnection({
    host     : 'localhost',  //mysql的服务器地址
    user     : 'root',     //用户名
    password : 'root', //密码
    database : '2020-03-13'  //数据库名
});

//3链接
connection.connect()


//插入
// let str1 = "INSERT INTO user (name,age,address) VALUES('李四',18,'中国湖北')"

//修改
// let str2 = `UPDATE user set name='lisi' WHERE name='李四'`

//删除
// let str3 = `DELETE FROM user WHERE name='sufei'`

//4查询
let str4 = `SELECT * FROM user`


//表相关的操作
// connection.query('sql语句', function (error, results, fields) {})

// app.get("/api/user",(req,res,next)=>{
//     connection.query(str4, function (error, results, fields) {
//         // console.log("error",error)
//         // console.log("results",results)
//         // console.log("fields",fields)

//         res.send({err:0,data:results})
//         //5关闭库
//         connection.end();
//     })
// })

mongodb

Non-relational database, known as nosql, cache type, multi-use scenarios to solve large-scale data collection of multiple types of data

  1. Download installation help

  2. Configuration data file storage location:

Find the installation directory \ Server \ 4.0 \ bin \ -> cmd Enter -> mongod Enter -> mongod --dbpath c: \ data \ db

data and db directory to be created manually

  1. The server start: Optional

Find the installation directory \ Server \ 4.0 \ bin \ -> cmd Enter -> mongod Enter

General will open the default startup

  1. Client starts:

Find the installation directory \ Server \ 4.0 \ bin \ -> cmd Enter -> mongo Enter

  1. Environment Variables Optional

In order to go on any letter can start mongod server | mongo client, add the environment variable to the installation directory

mysql vs mongodb

mysql mongoDb
database (library) database (library)
Table (Table) collection (the collection)
row (a data) document (document)
column (field) field (area)
Two-dimensional table, each time saved to disk json, cached, saved to disk when you close Storage

mongodb command line operation declarative | obj.api ()

Library operations

: show dbs
  	db 查看当前库
建:	use 库名	   没有建,有就切换
删: db.dropDatabase()  删除当前库

Set (table) Operation

建:db.createCollection('表名',{配置})
  //配置:{size:文件大小,capped:true,max:条数|文档数} capped定量
  //db.表(集合).isCapped() 返回 true/false 是否是定量
查:show collections / db.getCollectionNames()
删:db.|集合.drop()

Document (row) operation

increase

db.集合.save({}) //添加一条
db.集合.insert({})  //添加一条
db.insertOne({}) //添加一条

db.集合.save([{},{}]) //多条
db.集合.insert([{},{}]) //多条
//insert  不会替换相同ID	save会

delete

db.集合.deleteOne({要删数据条件描述}) //一条
db.集合.remove({},true)  //一条

db.集合.remove({要删数据条件描述}) //多条
db.集合.remove({}) //清空表

change

db.集合.udpate({查询条件},{替换条件},插入boolean,全替换boolean)

Query conditions

{age:22} age == 22
{age:{KaTeX parse error: Expected 'EOF', got '}' at position 6: gt:22}̲} age > 22 {a…lt:22}} age < 22
{age:{KaTeX parse error: Expected 'EOF', got '}' at position 7: gte:22}̲} age>=22 {ag…lte:22}} age<=22
{age:{ l t e : 122 , lte: 122, gte:22}} age<=122 && age>=22
{$or:[{age:22},{age:122}]} 22 or 122
{key:value,key2,value2} value && value2
{name:/正则/}

Replace condition

{ s e t : number according to , set: {data}, inc is: {Age:}}. 1

check

所有:db.集合.find(条件)
条数: db.集合.find().count()
去重:db.集合.distinct(key)

db.集合.find({条件},{指定要显示列区域})

Specify column display area

username: 1 display this area, others are not displayed

username: 0 will not show this area, other display

_id is the default display

row

db.集合.find().sort({key:1,key2:-1}) //升
db.集合.find().sort({key:-1})	//降

Limit

db.集合.find().limit(number)  //限定
db.集合.find().skip(number)	//跳过
db.集合.findOne()//找第一个
db.集合.find().limit(1)  //查询第一条
Published 21 original articles · won praise 0 · Views 300

Guess you like

Origin blog.csdn.net/weixin_43861707/article/details/104850395
Recommended