【问题标题】:Use of express.static middlewareexpress.static 中间件的使用
【发布时间】:2018-06-10 10:09:19
【问题描述】:

以下两个代码在服务器启动时在 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】:

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

    【讨论】:

    • 为什么会失败?有什么特别的原因吗?
    • 您对 sendFile 行所做的事情,Express 只是在客户端请求“/”方向时为您的 /index.html 提供服务,例如,如果客户端请求“/home.html”。 ExpressJS(实际上是 Node.JS)不会知道在哪里可以找到它,因为你从来没有告诉它它在哪里。使用app.use(express.static(publicPath)),您告诉 Express 它应该在 publicPath 中找到客户端请求的任何静态文件。如果你的 /index.html/ 包含一个 css,它也应该被提供,并且你从来没有告诉 Express 在哪里可以找到它(你用 express.static 行来做)。
    猜你喜欢
    • 1970-01-01
    • 2012-07-13
    • 1970-01-01
    • 2020-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-14
    • 1970-01-01
    相关资源
    最近更新 更多