express.static()定义
express.static(root, [options])是一个中间件函数,负责为Express应用提供静态资源服务。它允许你指定一个或多个目录作为静态资源的根目录,当客户端请求这些资源时,Express会查找并返回对应的文件。
安装express
npm install express
目录结构
基本用法
// 引入express
const express = require('express');
const app = express();// 指定静态资源目录
app.use(express.static('./resourceA'));
// 启动服务器
const PORT = 3000;
app.listen(PORT, () => {console.log(`Server is running on http://localhost:${PORT}`);
});
托管多个静态资源目录
// 引入express
const express = require('express');
const app = express();// 托管多个静态资源目录 express.static()函数会根据目录的添加循序查找所需文件,先找到的先访问
app.use(express.static('./resourceA'));
app.use(express.static('./resourceB'));
// 启动服务器
const PORT = 3000;
app.listen(PORT, () => {console.log(`Server is running on http://localhost:${PORT}`);
});
添加挂载路径前缀
// 引入express
const express = require('express');
const app = express();// 添加挂载路径前缀
app.use('/resourceA', express.static('./resourceA'));
app.use('/resourceB', express.static('./resourceB'));
// 启动服务器
const PORT = 3000;
app.listen(PORT, () => {console.log(`Server is running on http://localhost:${PORT}`);
});