Javascript 在Express中提供静态HTML文件的不同路径
只是一个简单的问题。假设我有两个不同的静态HTML文件,我想在Express中提供,Javascript 在Express中提供静态HTML文件的不同路径,javascript,node.js,express,Javascript,Node.js,Express,只是一个简单的问题。假设我有两个不同的静态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 (r
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')
});
问题是,我试图使用
app.get('/contact', function (req, res) {
res.sendFile(__dirname + '/contact.html');
});
但是它总是求助于根目录而不是公共目录。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
需要一个绝对路径,\u dirname
指的是您的应用程序目录。请确保根据文件位置提供引用。我想这会对您有所帮助,仅供参考:通过调试,您将看到app.get('/',function(req,res){
在您请求http://localhost:3000/
虽然可以使用node.js提供静态文件,但最好使用nginx。