在Express中提供静态HTML文件的不同路径

时间:2017-10-03 00:21:42

标签: javascript node.js express

只是一个简单的问题。假设我要在Express index.htmlcontact.html中提供2个不同的静态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

有谁能指出我的原因是什么?

感谢。

1 个答案:

答案 0 :(得分: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指的是您的应用目录。确保根据文件位置提供参考。