# 前言
Express
基于基于 Node.js 平台,快速、开放、极简的 Web 开发框架
# Express 项目生成器
全局安装脚手架
npm i express-generator -g | |
yarn global add express-generator |
查看版本
express --version |
# Express 创建应用
-h 参数可以列出所有可用的命令行参数
express -h |
可以设置模板引擎
express myapp -e | |
express myapp --pug | |
express --view=pug myapp |
初始化安装依赖
cd myapp | |
npm i 或 yarn |
# Express 启动应用
默认端口为 3000
npm start 或 yarn start |
# 修改端口号
在 app.js
中添加
process.env.PORT = 666; |
# 修改启动命令
使用 nodemon
npm i nodemon -g 或 yarn global add nodemon | |
nodemon |
# 配置路由
连接 mySql 数据库需要安装第三方依赖
npm install mysql -S |
这里导入后封装一个函数
const mysql = require('mysql') | |
function getConn() { | |
return mysql.createConnection({ | |
host: 'localhost', | |
port: '3306', | |
user: 'root', | |
password: '123456', | |
database: 'user' | |
}) | |
} |
response
负责后端发送给前端的响应数据request
负责接收前端请求的参数get
请求通过 req.query
接受参数post
请求通过 req.body
接受参数
是 36 万种子的裤子,简单封装一个接口给前端使用
router.get('/bt', (req, res, next) => { | |
let { type } = req.query | |
// 连接数据库 | |
const conn = btConn() | |
conn.connect() | |
// 查询数据库 | |
const str = `SELECT * FROM ${type} ORDER BY RAND() LIMIT 1;` | |
conn.query(str, (err, data) => { | |
if (err) throw err | |
res.send({ | |
code: 200, | |
msg: '请求成功', | |
data | |
}) | |
}) | |
// 关闭连接 | |
conn.end() | |
}); |