nodejs是一个基于Chrome V8引擎的JavaScript运行环境,使用了一个事件驱动、非阻塞式I/O模型,让JavaScript 运行在服务端的开发平台,它让JavaScript成为与PHP、Python、Perl、Ruby等服务端语言平起平坐的脚本语言。
nginx作为一个具有高性能的http、https、反向代理web服务器,非常适合托管静态资源文件。
通常我们使用Express框架来搭建一个nodejs web应用,这是一个非常不错的选择。现在我们通过一些例子来探讨今天的问题。
express 创建应用 基本实例
import express from "express";
const app = express();
// ... app.use、路由(app.get、app.post) 等。
// app.use(express.static("assets"));
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.listen(80, () => {
console.log(`port:${port}`)
})
express.static 直接挂载静态文件
app.use(express.static("assets"));
// http://localhost:8080/img/logo.png
// http://localhost:8080/css/index.css
express.static 添加别名/虚拟目录 挂载静态文件
app.use("/static", express.static("assets", { setHeaders }));
// http://localhost:8080/static/img/logo.png
// http://localhost:8080/static/css/index.css
sendFile 发送静态文件
比如说在多租户架构下,一个nodejs应用同时绑定N个站点。
举例:

多租户
// typescript 代码实例
sendFile(req: core.Request, res: core.Response, host_code:string) {
const filePath = `./sites/${host_code}${decodeURIComponent(req.path)}`;
res.sendFile(filePath, { root: path.resolve(".") }, (err) => {
if (err) {
// ...
}
});
}
在实际应用过程中,当访问量较大时,体验不是很完美。这个时候nginx登场了,完美的解决了相关问题,所以合理利用不同工具,争取做到尽善尽美,是乃毕生之所追求。
nginx 代理nodejs,并直接托管静态资源不走Nodejs
server{
listen 80;
server_name video.prvt.cool;
location / {
# ... 其它配置
proxy_pass http://127.0.0.1:9010;
}
location /css {
alias d://sites/web0015/assets/;
}
}
server{
listen 80;
server_name music.prvt.cool;
location / {
# ... 其它配置
proxy_pass http://127.0.0.1:9010;
}
location /css {
alias d://sites/web0017/assets/;
}
}
server{
listen 80;
server_name prvt.cool www.prvt.cool;
location / {
# ... 其它配置
proxy_pass http://127.0.0.1:9010;
}
location /css {
alias d://sites/web0016/assets/;
}
}
运行多个Node应用程序时
当您运行多个nodejs应用程序时,您希望他们都使用80端口时,这时候使用NGINX来代理,将会是一个完美的选择。
人人为我,我为人人,欢迎您的浏览,我们一起加油吧。