Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/373.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/40.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在Express中提供静态HTML文件的不同路径_Javascript_Node.js_Express - Fatal编程技术网

Javascript 在Express中提供静态HTML文件的不同路径

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

只是一个简单的问题。假设我有两个不同的静态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')
});
问题是,我试图使用

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。