Node-EXPRESS

/**
 * npm install express express-session body-parser
 * express   框架
 * express-session
 * body-parser   真实项目中处理 客户端通过POST请求基于请求主体传过来信息的解析
 */

const express = require('express'),
    config = require('./config'),
    // npm install body-parser
    bodyParser = require("body-parser"),
    app = express();

const fsPromise = require("./lib/myFs")
const { responseInfo } = require("./lib/utils")

/*创建服务监听端口*/
app.listen(config.port, _ => {
    console.log(`SERVER IS CREATE => ${config.port}`);
});

/*中间件:在处理请求之前统一做的事情*/
app.use(bodyParser.urlencoded({
    // => 把请求主体传递的信息 x-www-form-urlencoded 变为对象键值对的方式,存储到req.body上(bodyParser中间件完成的事情)
    extended: false
}))
app.use(async (req, res, next) => {
    req.USER_DATA = await fsPromise.readFile('./mock/user.json');
    req.USER_DATA = JSON.parse(req.USER_DATA)

    // 处理完当前的事情,让其继续向下匹配
    next()
});

/* API接口的请求处理*/
app.get('/api/list', (req, res) => {
    let { limit = 10, page = 1 } = req.query
    page = parseInt(page)
    limit = parseInt(limit)
    let total = req.USER_DATA.length,
        pages = Math.ceil(total / limit),
        data = [];
    for (let i = (page - 1) * limit; i < page * limit; i++) {
        let item = req.USER_DATA[i];
        if (!item) {
            break;
        }
        data.push(item);
    }
    if (data.length === 0) {
        responseInfo(res, {
            code: 1,
            codeText: "没有匹配数据!"
        })
        return
    }
    responseInfo(res, {
        page,
        limit,
        pages,
        total,
        data
    })
});

app.post('/api/add', (req, res) => {
    let { name = "", phone = "" } = req.body
    req.req.USER_DATA.push({
        id: req.USER_DATA.length === 0 ? 1 : parseInt(req.USER_DATA
        [req.USER_DATA.length - 1]['id']) + 1,
        name,
        phone
    });
    fsPromise.writeFile('./mock/user.json', req.USER_DATA).then(_ => {
        responseInfo(res)
    }).catch(_ => {
        responseInfo(res, {
            code: 1,
            codeText: "增加失败!"
        })
    });
});

/*静态资源文件的处理 */
app.use(express.static('./static'));
app.use((req, res) => {
    res.status(404).send({
        code: 1,
        codeText: 'not found!'
    });
});
// => utils.js(封装一个共有的提示信息)
function responseInfo(res, options) {
    let config = Object.assign({
        code: 0,
        codeText: 'OK!'
    }, options);
    res.status(200).type('application/json').send(config);
}

module.exports = {
    responseInfo
};
// => myFs.js(单独封装的异步操作)
const fs = require('fs'),
    path = require('path');


// => 读文件
function readFile(pathname, encoding = 'utf8') {
    return new Promise((resolve, reject) => {
        pathname = path.resolve(pathname);
        fs.readFile(pathname, encoding, (err, result) => {
            if (err) {
                reject(err);
                return;
            }
            resolve(result);
        });
    });
}


// => 写文件
function writeFile(pathname, data, encoding = 'utf8') {
    return new Promise((resolve, reject) => {
        if (typeof data !== "string") {
            data = JSON.stringify(data);
        }
        pathname = path.resolve(pathname);
        fs.writeFile(pathname, data, encoding, err => {
            if (err) {
                reject(err);
                return;
            }
            resolve();
        });
    });
}


module.exports = {
    readFile,
    writeFile
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值