nodejs服务器框架之express用法总结

const express = require("express");
const bodyParser = require("body-parser");
const cookieParser = require("cookie-parser");

const testRouter = require("./routes/test.js");
const bonusSystemRouter = require("./routes/bonus_system/transaction_record.js");
const assetTradeRouter = require("./routes/asset_trade/transaction_record.js");
const walletRouter = require("./routes/wallet/transaction_record.js");
const OwnExpressResponse = require("./common/OwnExpressResponse.js");
const app = express();

/**
 *  【第三方中间件或自定义中间件】在匹配路由之前会执行初始化代码块
 * **/

// 解析cookie数据【暂时还没用到】
app.use(cookieParser());

// 解析,用req.body获取post参数
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded


/**
 * 【路由中间件】执行路由匹配,一旦匹配成功,执行完毕之后会返回客户端结果【send返回】
 * **/

// 路由请求超时的中间件【必须放置在路由中间件之前,确保路由访问超时为120秒】
app.use(function (req, res, next) {
    // 这里必须是Response响应的定时器【默认设置120秒】
    res.setTimeout(120 * 1000, () => {
        console.log("Request has timed out.");
        return OwnExpressResponse.fail(res, "请求超时", 408);
    });
    next();
});


app.use("/node_api/v1/http", testRouter);
app.use("/node_api/v1/http/bonus_system/record", bonusSystemRouter);
app.use("/node_api/v1/http/asset_trade/record", assetTradeRouter);
app.use("/node_api/v1/http/wallet/record", walletRouter);

/**
 * 【错误处理中间件】
 *  404错误处理:仅当前面的路由未匹配才会执行到404,一旦匹配成功,路由执行完毕就返回send客户端数据!
 *  500错误处理:路由匹配成功,但是在执行过程中抛出了错误,才会调用Express的错误处理模块【没错误则不会调用】
 * **/

// 404 not Found错误处理【仅路由没有匹配才会执行到这里来】
app.use(function (req, res, next) {
    return OwnExpressResponse.fail(res, "not found request!", 404);
});


// 500 服务器错误处理【没有错误会跳过,不会执行!】
app.use(function (err, req, res, next) {
    console.error("express全局错误处理:error", err.stack);
    return OwnExpressResponse.fail(res, null, 500, { "error": err.stack });
});


/**
 * 【nodemon调试配置】
 * **/

// 使用 nodemon app.js 测试环境实时更新修改代码

let debug = require("debug")("my-application"); // debug模块
app.set("port", process.env.PORT || 9099); // 设定监听端口

//启动监听
let server = app.listen(app.get("port"), function () {
    debug("Express server listening on port " + server.address().port);
});


// 生成环境的时候加上导出,使用./bin/www来调用执行【测试环境暂时屏蔽】
// module.exports = app;

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值