在Express中提供静态HTML文件的不同路径
Just a quick question. Say I have 2 different static HTML files that I want to serve in Express, index.html
and contact.html
. I've been fiddling around and I currently use this barebone Express code to serve them:
只是一个简单的问题。假设我有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')
});
Question is, I tried to serve contact.html
using
问题是,我尝试使用contact.html
app.get('/contact', function (req, res) {
res.sendFile(__dirname + '/contact.html');
});
but it always resort to the root directory instead of the public directory. OTOH, I can server index.html
just fine without having to explicitly adding /public
in the response.
但它总是求助于根目录而不是公共目录。 OTOH,我可以服务器index.html就好了,而不必在响应中明确添加/ public。
Can anybody point me what's the cause for that?
任何人都可以指出我的原因是什么?
Thanks.
谢谢。
1 个解决方案
#1
0
For the given file structure:
对于给定的文件结构:
yourapp
|-- contact.html
|-- index.html
`-- server.js
The following code would work just fine:
以下代码可以正常工作:
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});
app.get('/contact', function (req, res) {
res.sendFile(__dirname + '/contact.html');
});
Assuming both index.html
and contact.html
have read access.
假设index.html和contact.html都具有读访问权限。
Remember, sendFile
requires an absolute path and __dirname
refers to your app directory. Make sure you give references according to your file location.
请记住,sendFile需要一个绝对路径,而__dirname指的是您的app目录。确保根据您的文件位置提供参考。
更多相关文章
- js金额数字格式化实现代码(三位加逗号处理保留两位置小数)
- 基于缓冲区数据创建文件
- 怎么javascript读取本地文件中的数据,并显示在html上
- Aptana Studio 3 IDE中有运行JavaScript代码的方法吗?
- js读写文件(ActiveXObject只支持ie7以前的版本)
- 使用没有后端脚本的Angularjs上传文件(例如PHP,JAVA等)
- 如何在JavaScript中编写适当的OOP代码?
- 高性能JavaScript代码高亮插件
- js“DOM事件”之鼠标事件、js的测试方法、js代码的放置位置