【发布时间】:2017-01-22 08:48:49
【问题描述】:
这似乎是文件路径的常见错误,但我的问题更奇怪,因为代码昨天运行良好但今天不行(而且我没有更改任何代码)。我的文件夹目录很简单:
-node_modules
-public
-css
-js
control_panel.html
index.html
app.js
packages.json
我在 app.js 中使用 Express 中间件来帮助渲染文件。
var express = require("express");
var app = express();
app.use(express.static("public"));
app.get('/', function get(req, res) {
res.sendFile('/index.html');
});
app.get('/control_panel', function get(req, res) {
res.sendFile('/control_panel.html');
});
当我尝试在浏览器中打开 index.html 时,没有问题,一切正常。但是,当我尝试在浏览器中打开 control_panel.html 时,我得到了Error: ENOENT: no such file or directory, stat '/control_panel.html' at Error (native)
导致问题的原因是什么?
【问题讨论】:
-
res.sendFile('/control_panel.html')将不起作用。control_panel.html文件不在路径'/control_panel.html'中。另外,无论如何,您应该在这些路线上使用express.static('public')。 -
@jfriend00 当我指定
app.use(express.static("public"));时,应用程序不会开始在“public”文件夹下查找文件。在这种情况下,control_panel.html 在 public -
不适用于
res.sendFile()。express.static()仅适用于传入请求。res.sendFile()需要文件的真实有效路径。 -
@jfriend00 是否有替代使用 res.sendFile() 处理 html 文件的方法?
-
替代用于什么目的?静态文件应使用
express.static()提供,没有理由为静态文件手动创建路由。
标签: node.js express path response webstorm