1. 简介
(1)express 是一个保持最小规模的灵活的node.js web应用程序开发框架,为web和移动应用程序提供一组强大的功能
(2)使用您所选择的各种 HTTP 实用工具和中间件,快速方便地创建强大的 API。
(3)Express 提供精简的基本 Web 应用程序功能,而不会隐藏您了解和青睐的 Node.js 功能。
(4)许多 流行的开发框架 都基于 Express 构建。
2. 全局安装
npm install -g express express-generator nodemon
express // 核心模块
express-generator // 生成脚手架
nodemon // 自动监测文件变化,重启
3. 项目创建及运行
express -e expressDemo // 项目创建
npm i // 安装依赖包
npm start // 运行
http://127.0.0.1:3000/ // 默认访问地址
4. 修改package.json 文件
node ==> nodemon 支持刷新重启
5. 目录结构及说明
bin:存放可执行文件
public:image、css、js 等资源
routes:路由文件
app.js:启动文件
views:ejs视图文件
6. 基本接口编写
// req 请求对象
// res 响应对象
// next 继续下一个中间件
const todos = [
{id: 0, title: '吃饭'},
{id: 1, title: '睡觉'},
{id: 2, title: '写代码'}
] // 实际情况数据来源于数据库
// 方式一 params参数 请求接口: http://127.0.0.1:3000/todos1/1
router.get('/todos1/:id', function(req, res, next) {
let sendData = todos.filter(todo => todo.id === req.params.id * 1)
res.send(sendData)
});
// 方式二 query参数 请求接口: http://127.0.0.1:3000/todos2?id=1
router.get('/todos2', function(req, res, next) {
if (req.query.id)
{
let sendData = todos.filter(todo => todo.id === req.query.id * 1)
res.send(sendData)
}else
res.send(todos)
});
7. 连接mysql
var express = require('express');
var router = express.Router();
const mysql = require("mysql");
// 创建连接
const db = mysql.createConnection({
host: "192.168.2.218",
user: "root",
password: "zbcx",
database: "gisscsw_dev"
});
// 连接数据库
db.connect( (err) => {
if(err) throw err;
console.log('连接成功');
});
// 查询内容
router.get("/yjfzb",(req,res) => {
let sql = "SELECT * FROM yjfzb";
db.query(sql,(err,result) => {
if (!err) return res.json(result)
})
});
module.exports = router;