【问题标题】: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

谁能指出这是什么原因?

谢谢。

【问题讨论】:

  • 仅供参考:通过调试,您会看到app.get('/', function (req, res) { 在您请求http://localhost:3000/ 时不会被调用
  • 虽然可以使用 node.js 提供静态文件,但最好使用 nginx。

标签: 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 指的是您的应用目录。确保根据您的文件位置提供参考。

【讨论】: