使用express.static中间件

问题描述 投票:0回答:1

以下两个代码在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中间件用于快递

node.js express static
1个回答
0
投票

不使用express.static will的代码在提供非index.html的任何其他静态页面时失败,即使index.html包含其他静态文件(作为css)也会失败。

© www.soinside.com 2019 - 2024. All rights reserved.