只是一个简单的问题。假设我要在Express index.html
和contact.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
。
有谁能指出我的原因是什么?
感谢。
答案 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.html
和contact.html
都具有读取权限。
请注意,sendFile
需要绝对路径,__dirname
指的是您的应用目录。确保根据文件位置提供参考。