Express的特点
- Express是Node.js的Web开发框架,上手简单,API丰富。
- 具有强大的路由功能和灵活的中间件机制。
- 适用于传统网站、API接口服务器、服务端渲染等。
- 性能强大,安全稳定。
简介
Express框架是一个高度包容的,快速而又极简的node.js外部框架。并且在实际的项目中使用的很多nodejs框架都是更据express二次封装的。
新建项目安装依赖
1. 初始化项目 安装依赖
npm init -y
命令的作用是: 对项目进行初始化操作,对包进行管理。-y 的含义:yes的意思,在init的时候省去了敲回车的步骤,生成的默认的package.json。
安装express 和 nodemon依赖
2. 新建入口文件app.js并且修改pack.json
{
"name": "myexpressporject",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev": "nodemon app.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.19.2"
}
}
启动服务绑定端口
1.引入express 全局挂载,创建服务
const express = require('express');
const app = express();
2. 监听端口
app.listen(3000, ()=>{
console.log('Run Htpp://127.0.0.1:3000')
})
使用 promisify解决回调地狱
Promise是一种异步编程的解决方案,它提供了统一的方式来处理各种异步操作,避免了回调地狱,使得异步编程更加合理和强
const fs = require('fs');
const {promisify} = require('util'); // 解决回调地狱问题
const readFile = promisify(fs.readFile); // 读文件
const writeFile = promisify(fs.writeFile); // 写文件
使用中间件
1. express.json() 作用
让我们能够通过 request.body 拿到请求体中 json 格式的数据。
2.express.urlencoded({ extended: true })
解析客户端发送的 URL 编码格式的请求体数据,将其转换为 JavaScript 对象,并将其赋值给 req.body。
通常用于处理通过表单提交的请求。
express 用户数据文件的操作
1.新建用户数据json文件
user.json 文件
{
"user": [
{
"id": "1",
"name": "zhangsan1",
"age": 12
},
{
"id": "2",
"name": "zhangsan2",
"age": 13
},
{
"id": "3",
"name": "姬无命",
"age": 11
},
{
"user": "里斯",
"age": 23,
"id": "31"
},
{
"user": "里斯",
"age": 23,
"id": "311"
}
],
"other": "other"
}
2.get请求 查询用户
app.get('/', async function(req, res){
try {
let back = await readFile('./bd.json', 'utf-8');
back = JSON.parse(back)
res.send(back.user);
}catch(erro){
res.send(erro)
}
})
另外一种写法
app.get('/', function(req, res){
readFile('./1bd.json','utf-8').then(data => {
const back = JSON.parse(data)
res.send(back.user);
}, err => {
console.log(111, err);
});
})
3.post 新增用户
// 添加
app.post('/', async(req, res)=>{
let body = req.body;
if(!body) {
res.status(403).json({
error: '缺少用户信息'
})
} else {
try {
let back = await readFile('./bd.json', 'utf-8');
const userInfoMap = JSON.parse(back)
const newid = userInfoMap.user[userInfoMap.user.length - 1].id + 1;
body.id = newid;
userInfoMap.user.push(body);
try {
let write = await writeFile('./bd.json', JSON.stringify(userInfoMap));
res.status(200).json({
sucess: '添加成功'
})
} catch (error) {
res.status(500).json({
error: error
})
}
} catch{
res.status(500).json({
error: error
})
}
console.log(body)
}
})
4. post 修改用户
app.put('/:id', async function(req, res){
const id = req.params.id;
console.log('id', id)
try {
let back = await readFile('./bd.json', 'utf-8'); // 读数据
let hasUser = false; // 是否找到这个ID的用户
back = JSON.parse(back)
back.user.forEach( async (item, index) => {
if(item.id === id) {
hasUser = true;
const obtuser = {...item, ...req.body}
back.user[index] = obtuser;
try {
let write = await writeFile('./bd.json', JSON.stringify(back));
res.status(201).json({
sucess: '修改成功'
})
} catch (error) {
res.status(500).json({
sucess: '修改失败'
})
}
}
});
if(!hasUser) {
res.status(203).json({
error: '查不到该用户'
})
}
}catch(erro){
res.send(erro)
}
})