【问题标题】:Different Path for Serving Static HTML files in Express在 Express 中提供静态 HTML 文件的不同路径
【发布时间】:2017-10-03 20:07:21
【问题描述】:

只是一个简单的问题。假设我想在 Express 中提供 2 个不同的静态 HTML 文件,index.htmlcontact.html。我一直在摆弄,我目前使用这个准系统 Express 代码为他们提供服务:

const express = require('express');
const path = require('path');

const app = express();

app.use(express.static('public'))

app.get('/', function (req, res) {
  res.sendFile('/index.html');
});

app.get('/contact', function (req, res) {
  res.sendFile(__dirname + '/public/contact.html');
});

app.listen(3000, function () {
  console.log('runnning on port 3000')
});

问题是,我尝试使用 contact.html 服务

app.get('/contact', function (req, res) {
  res.sendFile(__dirname + '/contact.html');
});

但它总是求助于根目录而不是公共目录。 OTOH,我可以很好地服务index.html,而无需在响应中明确添加/public

谁能指出这是什么原因?

谢谢。

【问题讨论】:

标签: javascript node.js express


【解决方案1】:

对于给定的文件结构:

yourapp
 |-- contact.html
 |-- index.html
 `-- server.js

以下代码可以正常工作:

app.get('/', function (req, res) {
  res.sendFile(__dirname + '/index.html');
});

app.get('/contact', function (req, res) {
  res.sendFile(__dirname + '/contact.html');
});

假设index.htmlcontact.html 都具有读取权限。

请记住,sendFile 需要绝对路径,而__dirname 指的是您的应用目录。确保根据您的文件位置提供参考。

【讨论】:

    猜你喜欢
    • 2017-07-30
    • 1970-01-01
    • 2018-02-08
    • 2012-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-07
    • 1970-01-01
    相关资源
    最近更新 更多