前端案例-31 express 服务器框架,路由的使用,以及mysql的连接

本文介绍了如何使用Express作为web服务器框架,讲解了路由的配置,并针对在连接MySQL8数据库时遇到的'caching_sha2_password'加密不支持问题,提出了修改用户加密模式的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. web服务器
// 导入express
const express = require('express')
const cors = require('cors')
    //导入自定义路由
const userRouter = require('./js/router.js')

// 创建web服务器

const app = express()
    // app.use(bodyParser.urlencoded({ extended: false }))
app.use(cors())
app.use(express.json())
app.use(express.urlencoded({ extended: false }))
    // app.use(express.urlencoded());
    //注册路由
    // app.use(bodyPaser.json) //在其他路由中间件前(尽可能靠前,以能够通过bodyPaser获取req.body)
    // app.use(bodyParser.urlencoded({ extended: false }))
app.use('/myapp', userRouter)
    // 定义中间件
    // var mv = function(err, req, res, next) {
    //     // console.log(err.message)
    //     // req.starttime = Date.now()
    //     res.send(err.message)
    //         // next()
    // }

// app.use(mv)
// app.get('/index', (req, res) => {
//     console.log('are you get?')
//     res.send("You are get")
// })


// app.use(express.static('./clock'))
// app.use('/ccc', express.static('./clock'))
// app.use('/abc', express.static('./clock'))


// 启动服务器
app.listen(80, () => {
    console.log('express server running on http://127.0.0.1')
})
  1. 路由
const express = require('express')
    //创建路由对象
const router = express.Router()
    // 定义中间件

//挂载路由
router.get('/index', (req, res) => {
    // throw new Error("访问index页面错误")
    console.log(req.body)
    res.send("You are get")
})

router.post('/index', (req, res) => {
    //除了设置express.json(),客户端在请求的时候也需要设置Content-Type:application/json,否则获取到的为空对象
    console.log(req.body)
    console.log(req.address)
    res.send({ name: "kathy", age: 15 })
})

router.put('/index', (req, res) => {
    console.log(req.port)
    console.log(req.ip)
    res.send({ name: "jack", age: 20 })
})

router.delete('/index', (req, res) => {
    res.send({ name: "delete", age: 20 })
})

router.get('/', (req, res) => {
        console.log(req.query)
        res.send(req.query)
    })
    //id 和 name 为自定义参数名
router.get('/index/:id/:name', (req, res) => {
    // console.log(req.query)
    res.send(req.params)
})

//导出路由
module.exports = router
  1. 数据库连接

注:如果链接的是mysql8新版本的数据库,因为node.js中的mysql模块并不完全支持mysql8的‘caching_sha2_password’加密方式,此时链接会报错:“ER_NOT_SUPPORTED_AUTH_MODE: Client does not support authentication protocol requested by server; consider upgrading MySQL client”。
解决:将mysql8的加密模式改为普通模式,"ALTER USER ‘root’@‘localhost’ IDENTIFIED WITH mysql_native_password BY ‘自己的密码’; "

const mysql = require('mysql')
    // 连接数据库
const db = mysql.createPool({
    host: 'localhost',
    user: 'root',
    password: 'mysql',
    database: 'mysql_node',
})

// 1.创建表
// db.query('create table if not exists my_books (No int unsigned primary key auto_increment, book_name varchar(200) not null)', (err, results) => {
//     if (err) {
//         return console.log(err.message)
//     }
//     console.log(results)
// })

//  2.插入数据方法一
// db.query(`insert into my_books values(0,'红楼梦')`, (err, results) => {
//     if (err) {
//         return console.log(err.message)
//     }
//     console.log(results)
// })

// 2. 插入数据方法二
// const info = { no: 0, bookname: "三国演义" }
// const sql = `insert into my_books values(?,?)`
// db.query(sql, [info.no, info.bookname], (err, results) => {
//     if (err) {
//         return console.log(err.message)
//     }
//     if (results.affectedRows === 1) {
//         console.log("数据插入成功!")
//     }
// })

// 2. 插入数据方法三
// 使用这种方法是info对象中的参数名需和数据库中存的字段名--对应
// const info = { no: 0, book_name: "围城" }
// const sql = `insert into my_books set ?`
// db.query(sql, info, (err, results) => {
//     if (err) {
//         return console.log(err.message)
//     }
//     if (results.affectedRows === 1) {
//         console.log("数据插入成功!")
//     }
// })

// 3.查询数据
db.query(`select * from my_books where status=1`, (err, results) => {
    if (err) {
        return console.log(err.message)
    }
    console.log(results)
})

// 4. 更新数据方法一
// const info = { no: 7, book_name: "生物进化论" }
// const sql = `update my_books set book_name=? where no=?`
// db.query(sql, [info.book_name, info.no], (err, results) => {
//     if (err) {
//         return console.log(err.message)
//     }
//     if (results.affectedRows === 1) {
//         console.log("数据更新成功!")
//     }
// })

// 4. 更新数据方法二
// const info = { no: 8, book_name: "时间简史" }
// const sql = `update my_books set ? where no=?`
// db.query(sql, [info, info.no], (err, results) => {
//     if (err) {
//         return console.log(err.message)
//     }
//     if (results.affectedRows === 1) {
//         console.log("数据更新成功!")
//     }
// })

// 5. 删除数据

// const sql = `delete from my_books where no=?`
// db.query(sql, 5, (err, results) => {
//     if (err) {
//         return console.log(err.message)
//     }
//     if (results.affectedRows === 1) {
//         console.log("数据删除成功!")
//     }
// })

// 6. 标记删除

// const sql = `update my_books set status=0 where no=?`
// db.query(sql, 3, (err, results) => {
//     if (err) {
//         return console.log(err.message)
//     }
//     if (results.affectedRows === 1) {
//         console.log("数据更新成功!")
//     }
// })
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值