【发布时间】:2017-10-03 20:07:21
【问题描述】:
只是一个简单的问题。假设我想在 Express 中提供 2 个不同的静态 HTML 文件,index.html 和 contact.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