第一步创建文件并初始化
yarn init
第二步安装依赖
yarn add express nodemon
nodemon 用于热更新
第三步创建功能文件 (bodyParser 已删除请忽略)
common/index.js
const fs = require('fs');
// promisify 异步处理
const { promisify } = require('util');
const path = require('path');
const readFile = promisify(fs.readFile)
// 获取 json 数据
const getFileData = async (fileName) => {
const filePath = path.join(__dirname, `../json/${fileName}.json`)
const data = await readFile(filePath, 'utf-8')
return JSON.parse(data)
}
module.exports = {
getFileData
}
json/userData.json
[ { "userName": "Fengchengzhi", "sex": "男", "age": 25, "mobile": 123456, "mailbox": "xxxxx", "password": "123456" }, { "userName": "root", "sex": "男", "age": 25, "mobile": 123456, "mailbox": "xxxxx", "password": "123456" } ]
router/login.js
const express = require('express');
// 获取 json 数据
const { getFileData } = require('../common');
const router = express.Router();
// 登录
router.post('/api/login', async(req, res) => {
global.isLogin = true
// 获取所有用户信息
const allUserInfo = await getFileData('userData')
const { userName, password } = req.body
const info = allUserInfo.find(item => item.userName == userName)
if (!info) {
res.json({
code: 500,
data: null,
message: '用户不存在!'
})
} else {
if (info.password !== password) {
res.json({
code: 500,
data: null,
message: '密码错误!'
})
} else {
res.json({
code: 200,
data: info,
message: '登录成功!'
})
}
}
})
// 退出登陆
router.post('/api/loginOut', (req, res) => {
global.isLogin = false
res.json({
code: 200,
data: null,
message: '退出登录成功!'
})
})
module.exports = router;
index.js
const express = require('express');
const app = express();
const login = require('./router/login');
const menu = require('./router/menu');
// 登录状态
global.isLogin = false
// 解析 application/json 数据
app.use(express.json())
// 解析 application/x-www-form-urlencoded 数据
app.use(express.urlencoded())
// 登录拦截
app.all('*', (req, res, next) => {
if (req.url !== '/api/login') {
if (!global.isLogin) {
return res.json({
code: 304,
data: null,
message: '未登录!'
})
}
}
next()
})
// router
app.use('/', login);
app.use('/', menu);
app.listen(5000, () => {
console.log('服务启动')
})
package.json
{ "name": "node-api", "version": "1.0.0", "main": "index.js", "license": "MIT", "dependencies": {"express": "^4.17.3", "nodemon": "^2.0.15" }, "scripts": { "start": "nodemon index.js" } }
启动 yarn start
测试结果 (注意这里的请求是做过跨域处理的)