繁体   English   中英

使用express.static中间件

[英]Use of express.static middleware

启动服务器时,以下两个代码均在localhost:3000 /处提供index.html。

使用express.static

const path = require('path');
const express = require('express'); 
const PORT = process.env.port || 3000;
const publicPath = path.join(__dirname, '../public');

var app = express();
app.use(express.static(publicPath));
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
})

使用app.get

const path = require('path');
const express = require('express');
const PORT = process.env.port || 3000;
const publicPath = path.join(__dirname, '../public');

var app = express();

app.get('/',(req,res) => {
  res.sendFile(publicPath + '/index.html');
})

app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
})

那么,为什么有人会选择express.static不是app.get来提供静态html文件。 static中间件在快递上有什么用

服务于不是index.html的任何其他静态页面时,不使用express.static will的代码express.static will失败,即使index.html包含其他静态文件(作为CSS)也将失败。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM