NodeJS Express 静态文件、中间件、路由案例

NodeJS Express

Express,构建在Node.js平台上的Web开发框架,通过中间件机制和路由系统简化了HTTP服务器的创建流程。支持快速搭建RESTful API服务,提供模板引擎整合功能,并能够与Azure Functions等云服务平台进行集成。作为MEAN技术栈的核心组件之一,Express是Web开发领域最受欢迎的Node.js框架。

Express 5.0 requires Node.js 18 or higher. 参考文档:https://www.expressjs.com.cn/5x/api.html

初始化项目:npm init -y

安装依赖:npm install express@5.1.0,卸载依赖:npm uninstall express

Express 代码

复制代码
const express = require('express')
const app = express()

// 中间件
const middleware = function (req, res, next) {
    console.log(req.path, "中间件函数.");
    req.time = Date.now()
    next();
}
app.use(middleware);

// 静态文件
const options = {
    dotfiles: 'ignore',
    etag: false,
    extensions: ['htm', 'html', 'png'],
    index: false,
    maxAge: '1d',
    redirect: false,
    setHeaders(res, path, stat) {
        res.set('x-timestamp', Date.now())
    }
};
app.use(express.static('public', options));


// 请求处理
app.get('/', (req, res) => {
    res.send('hello world -> ' + req.time);
})
app.all('/all', function (req, res) {
    res.send('all -> ' + req.time);
});

// admin
const admin = express()
// 当子程序被挂载到父程序时,mount事件被发射
admin.on('mount', (parent) => {
    console.log('Admin Mounted')
    console.log(parent)
})
admin.get('/', (req, res) => {
    console.log(admin.mountpath)
    res.send('Admin Homepage');
})
app.use(['/admin', '/manag*r'], admin)

// 路由
const router = express.Router()
router.get('/info/:id', (req, res, next) => {
    console.log(req.params.id)
    res.send('router. -> ' + req.time);
})
app.use('/user', router)

// 
const port = 3000;
app.listen(port, () => {
    console.log("http server running at http://127.0.0.1:" + port);
})
相关推荐
yexianglunbai3 小时前
中间件(Middleware)详解:概念、作用与实战
java·开发语言·中间件
染指111017 小时前
128.Agent-LangChain核心组件-中间件-调用模型的时候
人工智能·windows·中间件·langchain·agent
染指11101 天前
129.Agent-LangChain核心组件-自定义中间件-通过类实现(AgentMiddleware)
人工智能·中间件·langchain·agent·agents
程序猿乐锅2 天前
【黑马点评 | 第九篇】秒杀优化-异步实现
java·spring boot·redis·后端·spring·中间件·mybatis
Wx-bishekaifayuan2 天前
springboot社区扶贫救助管理系统13300-计算机课程设计、毕业设计
spring boot·后端·python·django·课程设计·express·旅游
Wx-bishekaifayuan2 天前
springboot甘肃特产服务平台50301-计算机课程设计、毕业设计
spring boot·后端·python·django·课程设计·express·旅游
FYKJ_20102 天前
express皖美特色农产品网售系统53118-计算机课程设计、毕业设计
javascript·vue.js·spring boot·mysql·typescript·spark·express
Wx-bishekaifayuan2 天前
django医院营收信息预测系统49414-计算机课程设计、毕业设计
spring boot·后端·python·django·课程设计·express·旅游
Wx-bishekaifayuan2 天前
springboot会议室预约管理系统42030-计算机课程设计、毕业设计
spring boot·后端·python·django·课程设计·express·旅游
Wx-bishekaifayuan2 天前
springboot贵州旅游系统55916-计算机课程设计、毕业设计
spring boot·后端·python·django·课程设计·express·旅游