第一步创建文件并初始化
yarn init
第二步安装依赖
yarn add body-parser express nodemon
body-parser 用于获取 body 参数, nodemon 用于热更新
第三步创建功能文件
comon/index.js
const fs = require('fs'); // promisify 异步处理 const { promisify } = require('util'); const path = require('path'); const readFile = promisify(fs.readFile) // 获取 json 数据 module.exports.getFileData = async (fileName) => { const filePath = path.join(__dirname, `../json/${fileName}.json`) const data = await readFile(filePath, 'utf-8') return JSON.parse(data) }
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/index.js
const bodyParser = require('body-parser'); // create application/json parser 用于获取 body 参数 const jsonParser = bodyParser.json() // create application/x-www-form-urlencoded parser // const urlencodedParser = bodyParser.urlencoded({ extended: false }) module.exports = { jsonParser }
router/login.js
const express = require('express'); // 用于获取 body 参数 const { jsonParser } = require('./index'); // 获取 json 数据 const { getFileData } = require('../common'); const router = express.Router(); // 登录 router.post('/api/login', jsonParser, 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: 200, data: null, message: '用户不存在!' }) } else { if (info.password !== password) { res.json({ code: 200, data: null, message: '密码错误!' }) } else { res.json({ code: 200, data: info, message: '登录成功!' }) } } }) // 退出登陆 router.post('/api/loginOut', jsonParser, (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'); // 登录状态 global.isLogin = false // 登录拦截 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.listen(5000, () => { console.log('服务启动') })
package.json
{ "name": "node-api", "version": "1.0.0", "main": "index.js", "license": "MIT", "dependencies": { "body-parser": "^1.19.2", "express": "^4.17.3", "nodemon": "^2.0.15" }, "scripts": { "start": "nodemon index.js" } }
启动 yarn start
测试结果 (注意这里的请求是做过跨域处理的)