只是一个简短的问题。假设我有 2 个不同的静态 HTML 文件要在 Express 中提供,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');
});
但它总是求助于根目录而不是公共(public)目录。 OTOH,我可以服务器 index.html
就好了,而不必在响应中显式添加 /public
。
有人能告诉我这是什么原因吗?
谢谢。
最佳答案
对于给定的文件结构:
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
是指您的应用程序目录。确保根据文件位置提供引用。
关于javascript - 在 Express 中提供静态 HTML 文件的不同路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46535496/